【发布时间】:2023-04-05 20:54:01
【问题描述】:
注意:问题在于没有在map 上添加回报,因此与Promise 无关
我正在尝试并行进行多个独立的 api 调用。 Promise.allSettled(<promise array>) 看起来很适合这种情况。这是我第一次尝试使用 Promise,所以我可能犯了一些明显的错误。
问题:然后在承诺解决/拒绝之前执行。 事情是按照带圆圈的数字表示的顺序打印的。
// typescript version: 3.9.9
async function startTest(testInfo: someObjectType[]): Promise<string> {
const arrPromise = testInfo.map((info) => { startRun(info) });
console.log(arrPromise); // ① prints [undefined, ..., undefined]
(Promise as any)
.allSettled(arrPromise)
.then(async (results: any) => { // it was omitted but await was used in then block
console.log('[resolved all]'); // ②
for (const result of results) {
if (result.status == 'fulfilled') {
console.log(`resolve ${result.value}`); // ③ undefined
}
}
});
return 'some string data';
}
async function startRun(info: someObjectType): Promise<testResult|string> {
try {
const resp = await httpRequestHandler.post(`<request url>`, {request header});
if (resp.statusCode == 200) return 'some test result object';
} catch (ex) {
console.log(`[failed]=${info.testName}`); // ④
return Promise.reject(`${info.testName}: ${ex}`);
}
}
【问题讨论】:
-
您可以只使用
throw而不是return Promise.reject。但请注意,您应该始终throw errors, not strings。还要避免awaiting a.then(…)chain!就做const results = await Promise.allSettled(arrPromise);
标签: javascript typescript promise es6-promise