gpt4 book ai didi

javascript - 稍后捕获 Promise 拒绝

转载 作者:IT老高 更新时间:2023-10-28 23:11:07 26 4
gpt4 key购买 nike

我如何在以后检索 promise 的结果?在测试中,我在发送更多请求之前检索了一封电子邮件:

const email = await get_email();
assert.equal(email.subject, 'foobar');
await send_request1();
await send_request2();

在缓慢的电子邮件检索过程中如何发送请求?

起初,我考虑过等一下邮件:

// This code is wrong - do not copy!
const email_promise = get_email();
await send_request1();
await send_request2();
const email = await email_promise;
assert.equal(email.subject, 'foobar');

这在 get_email() 成功时有效,但如果 get_email() 在相应的 await 之前失败,则失败,并带有完全合理的 UnhandledPromiseRejectionWarning.

当然,我可以使用 Promise.all,像这样:

await Promise.all([
async () => {
const email = await get_email();
assert.equal(email.subject, 'foobar');
},
async () => {
await send_request1();
await send_request2();
},
]);

但是,它使代码更难阅读(它看起来更像基于回调的编程),特别是如果以后的请求实际上依赖于电子邮件,或者存在一些嵌套。是否可以存储 promise 的结果/异常并在以后 await 它?

如果需要,here is a testcase模拟有时会失败,有时会工作,时间随机。它绝不能输出 UnhandledPromiseRejectionWarning

最佳答案

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const send_request1 = () => wait(300), send_request2 = () => wait(200);
async function get_email() {
await wait(Math.random() * 1000);
if (Math.random() > 0.5) throw new Error('failure');
return {subject: 'foobar'};
}

const assert = require('assert');
async function main() {
// catch possible error
const email_promise = get_email().catch(e => e);
await send_request1();
await send_request2();
// wait for result
const email = await email_promise;
// rethrow eventual error or do whatever you want with it
if(email instanceof Error) {
throw email;
}
assert.equal(email.subject, 'foobar');
};

(async () => {
try {
await main();
} catch(e) {
console.log('main error: ' + e.stack);
}
})();

关于javascript - 稍后捕获 Promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com