[英]then block executed before promise resolves/reject (Promise.allSettled)
note: The issue was in not putting return on map
so not related with Promise
注意:问题在于没有在
map
上返回,因此与Promise
I'm trying to to make multiple, independent api calls in parallel.我正在尝试并行进行多个独立的 api 调用。
Promise.allSettled(<promise array>)
looked right for this scenario. Promise.allSettled(<promise array>)
看起来适合这种情况。 This is my first try to ever use promise, so I might have made some obvious mistakes.这是我第一次尝试使用 promise,所以我可能犯了一些明显的错误。
The issue: then was executed before promise resolve/reject.问题:然后在 promise 解决/拒绝之前执行。 Things were printed in order indicated with circled numbers.
事情是按照带圆圈的数字表示的顺序打印的。
// 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}`);
}
}
It's not related to Promise.allSettled
:它与
Promise.allSettled
:
const arrPromise = testInfo.map((info) => { startRun(info) }); console.log(arrPromise); // ① prints [undefined, ..., undefined]
arrPromise
should be an array of promises, but isn't: you're not returning them from the map
callback. arrPromise
应该是一组承诺,但不是:您不会从map
回调中返回它们。 Use利用
const arrPromise = testInfo.map((info) => { return startRun(info) });
// ^^^^^^
or或者
const arrPromise = testInfo.map(info => startRun(info));
or just要不就
const arrPromise = testInfo.map(startRun);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.