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!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ron Melkhior
  • 435
  • 2
  • 4
  • 13

1 Answers1

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.

Joseph
  • 117,725
  • 30
  • 181
  • 234