子异步回调函数的错误句柄

苏罗吉特·保罗
 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();

想要处理main函数的catch块内的subCallbackFunction回调错误。

出现错误

(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.
德米特里(Dmitriy Mozgovoy)

只需使您的主要函数异步,然后将await用于嵌套的异步函数即可:

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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章