Unexpected identifier when using await

Ron Melkhior picture Ron Melkhior · Apr 8, 2017 · Viewed 14.9k times · Source

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!

Answer

Joseph picture Joseph · Apr 8, 2017

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.