[英]Promise.all versus foreach Promise
我有一個 Angular 計算器應用程序,它計算一些按表格分組的結果( CalculatorResult
)(如Excel 表格)。 假設我們有六張紙。
我有一個方法, calculateSheet
,它需要一些屬性,工作表名稱,並返回一些CalculatorResult[]
:
async calculateSheet(
propertyValues: PropertyValue[],
sheetTypeName: string): Promise<CalculatorResult[]>
計算所有六張工作表的方法calculateSheets
應該計算六張工作表中的每一張,然后將結果的所有結果數組聚合到一個數組中(CalculatorResult 的六個數組應該成為一個)。
所以,我嘗試了兩種方法來聚合它,如下:
// define all promises to be calculated
const promises: (() => Promise<CalculatorResult[]>)[] = [this.selectedSheetTypeName, ...(sheets.value as Sheet[]).map((sheet: Sheet) => sheet.type.name)
.filter((sheetTypeName: string) => sheetTypeName != this.selectedSheetTypeName)]
.map((sheetTypeName: string) => this.calculateSheet.bind(this, propertyValues, sheetTypeName));
// now, await all results, and build a common array from 6 arrays(one per sheet) of results
let results: CalculatorResult[] = [];
// WHERE IS THE DIFFERENCE OF
// THIS ONE
const myValues = await Promise.all(promises);
console.log("All 6 sheets promises here bellow:");
console.log(myValues);
// VERSUS THIS ONE
for (const promise of promises) {
let sheetResults = await promise();
console.log("Sheet results:")
console.log(sheetResults)
results.push(...sheetResults);
console.log("All results:")
console.log(results)
}
在第一種情況下( myValues
),為什么我們有六個函數作為結果,而不是 CalculatorResults 數組?
根據經驗:
Promise.all
for Promise
首先,在您的示例中, promises
數組實際上是一個函數數組,您永遠不會執行它,這就是Promise.all
返回所有 fns 的原因。 使固定:
const promises = ….map((sheetTypeName: string) => this.calculateSheet(propertyValues, sheetTypeName));
Promise.all
如果所有的承諾都成功了:
如果任何承諾被拒絕:
for promises
主要區別在於會按順序執行每個函數。 它將等待執行並完成第一個,然后執行第二個,依此類推。
此外,您控制流程,因此如果第一個失敗,您可以選擇繼續或不繼續,或者做什么。
順便說一句,我永遠不會使用 bind 來實現它,會直接在for
中執行每個方法/函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.