Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected identifier when using await

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!

like image 425
Ron Melkhior Avatar asked Apr 07 '17 23:04

Ron Melkhior


People also ask

How do you fix an unexpected identifier?

To solve the "Uncaught SyntaxError: Unexpected identifier" error, make sure you don't have any misspelled keywords, e.g. Let or Function instead of let and function , and correct any typos related to a missing or an extra comma, colon, parenthesis, quote or bracket.

Does await stop code execution?

Promise creation starts the execution of asynchronous functionality. await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.

Can we return value from async function?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.


1 Answers

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.

like image 147
Joseph Avatar answered Sep 24 '22 06:09

Joseph