Different behavior of async functions when assigning temporary to variable

前端 未结 3 2016
半阙折子戏
半阙折子戏 2020-12-11 13:52

Why a different result in the following cases? The first example works correctly, returns an array of three elements [\"qwe\", \"rty\", \"asd\"]. Second example

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 14:46

    Concurrency. Or more precisely: A non atomic modification of values.

    First of all, the values.concat(...) get evaluated, at that time values is an empty array. Then all the functions await. Then, all the values = get run, concatenating the awaited element to the empty array, and assigning those arrays with one value to values. The last resolved value wins.

    To fix:

     await Promise.all(
      keys.map(
        async key => {
           const el = await this.getValue(key); // async operation
          values = values.concat(el); // atomic update
        }
      )
    );
    

提交回复
热议问题