Hen*_*ges 1 javascript node.js async-await
当我在 node 中创建一个异步函数并使用await 时,我让执行等待承诺解决(可以是解决或拒绝),我所做的是将await承诺放在 try/catch 块中并抛出承诺拒绝时的错误。问题是,当我在 try/catch 块中调用这个异步函数来捕获错误时,我得到一个UnhandledPromiseRejectionWarning。但是使用await的全部意义不是等待承诺解决并返回它的结果?似乎我的异步函数正在返回一个承诺。
示例 - UnhandledPromiseRejectionWarning代码:
let test = async () => {
let promise = new Promise((resolve, reject) => {
if(true) reject("reject!");
else resolve("resolve!");
});
try{
let result = await promise;
}
catch(error) {
console.log("promise error =", error);
throw error;
}
}
let main = () => {
try {
test();
}
catch(error){
console.log("error in main() =", error);
}
}
console.log("Starting test");
main();
Run Code Online (Sandbox Code Playgroud)
异步函数总是返回承诺。事实上,它们总是返回原生的 promise(即使你返回了一个 bluebird 或一个常量)。async/await 的目的是减少.then回调地狱的版本。你的程序仍然必须.catch在主函数中至少有一个来处理任何到达顶部的错误。
对于顺序异步调用来说真的很好,例如;
async function a() { /* do some network call, return a promise */ }
async function b(aResult) { /* do some network call, return a promise */ }
async function c() {
const firstRes = (await (a() /* promise */) /* not promise */);
const secondRes = await b(firstRes/* still not a promise*/);
}
Run Code Online (Sandbox Code Playgroud)
await没有在函数内部,你就不能做某事。通常这意味着您的main函数init或任何您调用的函数不是异步的。这意味着它不能调用await并且必须用于.catch处理任何错误,否则它们将是未处理的拒绝。在节点版本的某个时刻,这些将开始删除您的节点进程。
想想async为返回原生的承诺-不管是什么-以及await作为展开承诺“同步”。
请注意异步函数返回本机承诺,这些承诺不会同步解析或拒绝:
Promise.resolve(2).then(r => console.log(r)); console.log(3); // 3 printed before 2
Promise.reject(new Error('2)).catch(e => console.log(e.message)); console.log(3); // 3 before 2
Run Code Online (Sandbox Code Playgroud)异步函数将同步错误作为被拒绝的承诺返回。
async function a() { throw new Error('test error'); }
// the following are true if a is defined this way too
async function a() { return Promise.reject(new Error('test error')); }
/* won't work */ try { a() } catch(e) { /* will not run */ }
/* will work */ try { await a() } catch (e) { /* will run */ }
/* will work */ a().catch(e => /* will run */)
/* won't _always_ work */ try { return a(); } catch(e) { /* will not usually run, depends on your promise unwrapping behavior */ }
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
3479 次 |
| 最近记录: |