1

I want to test use loop to await.


// works fine
async function asyncFunc() {
    let arr = ['a', 'b', 'c'];

    for (let i = 0; i < arr.length; i++) {
        console.log(await arr[i]);
    }
}

asyncFunc()

async function asyncFunc() {
    let arr = ['a', 'b', 'c'];

    arr.forEach(function(el) {    // get an error:  SyntaxError: missing ) after argument list
        console.log(await el);
    })
}

asyncFunc()

async function asyncFunc() {
    let arr = ['a', 'b', 'c'];

    arr.forEach((el) => {        // get an error here:  SyntaxError: missing ) after argument list
        console.log(await el);
    })
}

asyncFunc()

Can someone tell me what's wrong here?

editor: VS code
node: 8.0.0

I know that i can't use await out of the current async function context.

So i am sure i will get an error on the second one.

But i do not know why i also get an error on the third one. Does the arrow function and the async function have the different context ???

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
percy507
  • 710
  • 9
  • 11
  • I'm pretty sure you're getting the error on the line below your comment, right? – Bergi Jul 16 '17 at 13:57
  • You're trying to use `await` in a function that is not an `async` function (the `forEach()` callback function). – Pointy Jul 16 '17 at 13:57
  • In what environment are you getting that error message? It's not super helpful - it should rather say that the `await` keyword cannot be used there. – Bergi Jul 16 '17 at 13:58
  • @Bergi isn't `await` parsed as a plain identifier in contexts where it can't be used? Or maybe I'm thinking of something else. – Pointy Jul 16 '17 at 14:01
  • @Pointy Yes, that's what happens here - it expects either `console.log(await)` or `console.log(await, el)` or something, so that's why it's complaining about a missing parenthesis. Which is what I'd call "not helpful" – Bergi Jul 16 '17 at 14:02
  • @Bergi I update the question just now, could you take a glance? thank u – percy507 Jul 16 '17 at 14:50
  • Yes, it does not matter whether it's an arrow function or a function expression or any other function syntax, they're two different functions. – Bergi Jul 16 '17 at 20:54
  • `async/await` is part of ES2017, not ES2016. – Felix Kling Jul 17 '17 at 17:05

0 Answers0