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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With