Unexpected identifier when using await
Asked Answered
A

1

18

I'm currently trying to use async/await for a function that requires the loop to be synchronous.

This is the function:

async channelList(resolve, reject) {
    let query = ['channellist'].join(' ');

    this.query.exec(query)
    .then(response => {
        let channelsRaw = response[0].split('|');
        let channels = [];

        channelsRaw.forEach(data => {
            let dataParsed = ResponseParser.parseLine(data);

            let method = new ChannelInfoMethod(this.query);
            let channel = await method.run(dataParsed.cid);

            channels.push(channel);
        });

        resolve(channels);
    })
    .catch(error => reject(error));
}

When I try to run it, I get this error:

let channel = await method.run(dataParsed.cid);
                    ^^^^^^
SyntaxError: Unexpected identifier

What could be the cause of it?
Thanks!

Archambault answered 7/4, 2017 at 23:44 Comment(0)
D
51

Your async is defined on channelList and not on the arrow function where the await is contained. Move async to that arrow function:

channelsRaw.forEach(async (data) => {
    let dataParsed = ResponseParser.parseLine(data);

    let method = new ChannelInfoMethod(this.query);
    let channel = await method.run(dataParsed.cid);

    channels.push(channel);
});

Also, since you're using async anyways, you can just async the entire promise chain you have there.

Dishpan answered 7/4, 2017 at 23:55 Comment(2)
I feel so silly now, didn't realize it was in a callback. Thanks :)Archambault
I made the same mistake, I wasn't thinking of anonymous functions as actually being functions!Grim

© 2022 - 2024 — McMap. All rights reserved.