【问题标题】:How to use Promise.all correctly?如何正确使用 Promise.all?
【发布时间】:2019-06-11 19:16:19
【问题描述】:

考虑以下代码:

var result1;
var result1Promise = getSomeValueAsync().then(x => result1 = x);

var result2;
var result2Promise = getSomeValueAsync().then(x => result2 = x);

await Promise.all([result1Promise, result2Promise]);

// Are result1 and result2 guaranteed to have been set at this point?

console.log(result1 + result2); // Will this always work? Or could result1 and/or result2 be undefined because then() has not been executed yet?

当我使用 then() 方法时,是否保证已按顺序执行?例如。解决 Promise.all 后 then() 不会立即执行?

它在 Chrome 中似乎可以正常工作,但我真正想要的是保证它始终可以按照某些规范工作?

我宁愿不使用 Promise.all(...).then(some callback) 因为那样我又要重新使用回调了...

【问题讨论】:

  • 是的,可以,.then 只是 await 的替代品
  • @CertainPerformance Yes :) 但我认为您错过了问题的重点,即 then() 回调的执行顺序。例如,如果第 1 行的 then() 回调在 Promise.all 的 then 之后执行,它将不起作用。
  • 您是否更愿意为外部变量赋值而不是使用Promise.all 调用的返回值?
  • @SamuelVaillant 啊!这就是我应该做的。我不知道 Promise.all 返回了这些值。

标签: javascript asynchronous


【解决方案1】:

可以直接使用Promise.all的返回值:

const p1 = getSomeValueAsync();
const p2 = getSomeValueAsync();

const [result1, result2] = await Promise.all([p1, p2]);

console.log(result1 + result2);

【讨论】:

    【解决方案2】:

    Promise.all 只有在其数组中的所有承诺都解决后才会解决。因为你的两个 Promise 有 .thens 的:

    .then(x => result1 = x);
    .then(x => result2 = x);
    

    这两个函数都完成后,Promise.all 将解析。所以是的,result1result2 都保证在 Promise.all 回调运行时被定义(或至少已被分配)。

    尽管如此,与分配给外部变量相比,使用const 定义变量可能更有意义 awaiting Promise.all

    const [result1, result2] = await Promise.all([getSomeValueAsync(), getSomeValueAsync()]);
    

    【讨论】:

    • 但是即使数组中的promise已经解决了,也不能保证那些promise的then()已经被执行了?
    • 是的,它确实如此 - 表达式解析为的 Promise 只有在所有链接的 .then 回调完成后才会解析。请参阅stackoverflow.com/questions/55565326/…,它可能会让事情变得更清楚一些。每次调用.then,都会创建一个新的 Promise
    【解决方案3】:

    是的,它们已经设置好了。解析 result1Promise 和 result2Promise 包括设置 result1 和 result2 因为 promise 本身只有在 .then() 执行时才会完全解析。

    但如果你想完全避免回调,你应该像这样构造你的代码:

    const result1Promise = getSomeValueAsync();
    const result2Promise = getSomeValueAsync();
    
    const results = await Promise.all([result1Promise, result2Promise]);
    
    console.log(results[0] + results[1]);
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2016-09-06
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 2021-02-17
      • 2016-11-05
      相关资源
      最近更新 更多