Javascript 来自子异步回调函数的错误句柄
要在主函数的catch块内处理subCallbackFunction回调错误 这是一个错误Javascript 来自子异步回调函数的错误句柄,javascript,node.js,Javascript,Node.js,要在主函数的catch块内处理subCallbackFunction回调错误 这是一个错误 function main(){ try { subCallbackFunction(1,(err,res) =>{ if(err){ throw Error(err); } }) } catch (e) { /// Want to handle err from here
function main(){
try {
subCallbackFunction(1,(err,res) =>{
if(err){
throw Error(err);
}
})
} catch (e) {
/// Want to handle err from here //////
console.log("Error handle block",e)
}
}
////// subCallbackFunction ////
async function subCallbackFunction(arg, callback){
await waitFor(2000);
//sending error///
callback("My error")
}
/// Wait Promise //
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
/// call main function /////
main();
只需将主函数设置为异步,并将wait用于嵌套异步函数:
(node:1081) UnhandledPromiseRejectionWarning: Error: My error
(node:1081) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1081) [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.
或:
async function main(){
try {
await subCallbackFunction(1,(err,res) =>{
if(err){
throw Error(err);
}
})
} catch (e) {
/// Want to handle err from here //////
console.log("Error handle block",e)
}
}
////// subCallbackFunction ////
async function subCallbackFunction(arg, callback){
await waitFor(2000);
//sending error///
callback("My error")
}
/// Wait Promise //
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
/// call main function /////
main();
function main() {
subCallbackFunction(1, (err, res) => {
if (err) {
throw Error(err);
}
}).catch(e => {
console.log("Error handle block", e)
})
}
////// subCallbackFunction ////
async function subCallbackFunction(arg, callback){
await waitFor(2000);
//sending error///
callback("My error")
}
/// Wait Promise //
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
/// call main function /////
main();