如何正确使用Promise.all?

Hel*_*rld 2 javascript asynchronous

考虑以下代码:

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

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

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

我宁愿不使用Promise.all(...)。then(某些回调),因为那样的话我会再次使用回调...

Sam*_*ant 9

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

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

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

console.log(result1 + result2);
Run Code Online (Sandbox Code Playgroud)


Cer*_*nce 5

Promise.all只有在其数组中的所有promise均解决后,才会解析。因为您的两个Promise都具有.then

.then(x => result1 = x);
.then(x => result2 = x);
Run Code Online (Sandbox Code Playgroud)

Promise.all两个功能均完成后,即可解决。因此,可以result1result2并且保证在Promise.all回调运行时定义和(或至少已分配给)。

不过,与其分配给外部变量,不如分配外部变量,const await在时使用来定义变量可能更有意义Promise.all

const [result1, result2] = await Promise.all([getSomeValueAsync(), getSomeValueAsync()]);
Run Code Online (Sandbox Code Playgroud)