async / await不能在forEach中工作

时间:2016-07-31 05:21:22

标签: javascript asynchronous async-await ecmascript-6

尝试在forEach

中使用async / await时获取意外的令牌
    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);
    }

这是错误:

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);

2 个答案:

答案 0 :(得分:4)

await应该在async函数中使用,它用于forEach回调,这是常规函数。

即使async函数作为forEach回调提供,也无法获取承诺,因为forEach不返回任何内容。

为此,应手动形成承诺链。

  appState.loadBunny = async function(bugs) {
    let promise = Promise.resolve();

    bugs.forEach(function(data) {
      promise = promise.then(async function () {
        let temp = {};
        ...
      });
    });

    await promise;
  }

这就是for...of函数中async必不可少的原因:

  appState.loadBunny = async function(bugs) {
    for (const data of bugs) {
      let temp = {};
      ...
    });
  }

在这种情况下,生成器函数和yield的行为类似。

答案 1 :(得分:3)

return (dynamic)this;仅适用于await函数,如下所示:

async

因此,您应该重构代码,以便这些async function test() { await myObj.setObj(2, 3); console.log(obj.a + obj.b); } test(); 调用位于他们自己的await decrypt(sessionStorage.getItem('key'), data.email函数中。