4

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);
pyprism
  • 2,928
  • 10
  • 46
  • 85

2 Answers2

5

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
3

await only works inside an async function, like this:

async function test() {
    await myObj.setObj(2, 3);

    console.log(obj.a + obj.b);
}

test();

As so, you should refactor your code so that those await decrypt(sessionStorage.getItem('key'), data.email calls are inside their own async functions.

David Gomes
  • 5,644
  • 16
  • 60
  • 103