Get unexpected token when trying to use async/await in forEach
export let appState = observable({
bunny : []
});
appState.loadBunny = async function(bugs) {
bugs.forEach(function(data) {
let temp = {};
temp['id'] = data.id;
temp['site_url'] = data.site_url;
temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
temp['password'] = await decrypt(sessionStorage.getItem('key'), data.password);
temp['note'] = await decrypt(sessionStorage.getItem('key'), data.note);
temp['tag'] = await decrypt(sessionStorage.getItem('key'), data.tag);
temp['created_at'] = data.created_at;
temp['updated_at'] = data.updated_at;
runInAction("update state after decrypting data", () => {
this.bunny.push(temp);
});
});
};
appState.fetch = async function() {
let xoxo = await axios.get('/api/vault/', {
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
});
this.loadBunny(xoxo.data);
}
and here is the error:
ERROR in ./static/apps/store/passwords.js
Module build failed: SyntaxError: ...static/apps/store/passwords.js: Unexpected token (15:30)
13 | temp['id'] = data.id;
14 | temp['site_url'] = data.site_url;
> 15 | temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
| ^
16 | temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
await
should be used in async
function, and it is used in forEach
callback, which is regular function.
Even if async
function is provided as forEach
callback, a promise cannot be obtained because forEach
returns nothing.
To do this, promise chain should be formed manually.
appState.loadBunny = async function(bugs) {
let promise = Promise.resolve();
bugs.forEach(function(data) {
promise = promise.then(async function () {
let temp = {};
...
});
});
await promise;
}
This is the reason why for...of
is essential in async
functions:
appState.loadBunny = async function(bugs) {
for (const data of bugs) {
let temp = {};
...
});
}
Generator functions and yield
behave similarly in such cases.
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