簡體   English   中英

如何正確使用Promise.all?

[英]How to use Promise.all correctly?

請考慮以下代碼:

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(...)。然后(一些回調),因為那時我又回到了使用回調...

只有在其數組中的所有promise都已解決后, Promise.all才會解析。 因為你的兩個承諾有以下.then

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

一旦這兩個功能完成, Promise.all將解決。 所以是的,當Promise.all回調運行時, result1result2都保證被定義(或者至少被分配給)。

仍然,不是分配外部變量,而是 await Promise.allconst定義變量更有意義:

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

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

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

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

console.log(result1 + result2);

是的,他們已經確定。 解析result1Promise和result2Promise包括設置result1和result2,因為只有在執行.then()時才能完全解析promise本身。

但是,如果你想避免回調,你應該像這樣構建你的代碼:

const result1Promise = getSomeValueAsync();
const result2Promise = getSomeValueAsync();

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

console.log(results[0] + results[1]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM