【发布时间】:2020-08-20 06:32:41
【问题描述】:
我想等待两个并行运行的 Promise。我不想连续等待每个承诺(这有效但速度较慢)。
出于这个原因,我认为我可以首先创建两个 Promise 来让它们滚动,比如两个网络请求,然后等待它们并能够在 catch 块中捕获错误。这个假设似乎不正确,因为我在运行此示例代码时收到警告。
- 这是为什么呢?
- 我如何最好地使用优雅的代码并行运行两个或多个网络请求?
- 为什么 Typescript 没有警告我 catch-block 不会 抓住拒绝?
async function testMultipleAwait() {
try {
const aPromise = new Promise((resolve) => {
setTimeout(() => resolve('a'), 200);
});
const bPromise = new Promise((_, reject) => {
setTimeout(() => reject('b'), 100);
});
const a = await aPromise;
const b = await bPromise;
} catch (e) {
console.log('Caught error', e);
}
}
testMultipleAwait();
不会导致“捕获错误”输出,而是得到
tsc test-try-catch-await.ts && node test-try-catch-await.js
(node:31755) UnhandledPromiseRejectionWarning: b
(node:31755) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:31755) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Caught error b
(node:31755) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
【问题讨论】:
标签: node.js typescript async-await