异步/等待在 forEach 中不起作用

pyp*_*ism 3 javascript asynchronous async-await ecmascript-6

尝试使用 async/await 时获取意外令牌 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);
    }
Run Code Online (Sandbox Code Playgroud)

这是错误:

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);
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 5

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;
  }
Run Code Online (Sandbox Code Playgroud)

这就是为什么for...ofasync函数中必不可少的原因:

  appState.loadBunny = async function(bugs) {
    for (const data of bugs) {
      let temp = {};
      ...
    });
  }
Run Code Online (Sandbox Code Playgroud)

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