【问题标题】:Throw a value error in the main thread from a callback从回调中在主线程中抛出值错误
【发布时间】:2020-12-03 13:28:48
【问题描述】:

我是 JavaScript 的初学者,当第三方异步函数发生错误时,我很难在主线程中抛出消息错误:

function mainThread(){
   try{
         myFunction(param1, error => {
            throw error // Error is not catched
         })
      }
   catch (error)
   {
      "i would like to catch the error here in the main thread"
   }
}


function myFunction(param1, callback) {
    asyncThirdpartyfunction(param1, (err) => {
        if (err)
            callback(err)
         
    })
}

错误在我的控制台中被抛出,没有被 catch 处理。 怎么了?我该怎么做才能在我的主线程中获取错误值? 我尝试了很多回调和承诺的事情,但他们没有做我想要的。

【问题讨论】:

    标签: javascript callback throw


    【解决方案1】:

    如果asyncThirdpartyfunction返回一个promise,你可以使用catch来处理错误:

    asyncThirdpartyfunction(param1, (err) => {
        if (err)
            callback(err)
         
    })
    .catch(err => alert(err))
    

    【讨论】:

    • 非常感谢您的回答。我已经测试了你的例子,我有一个错误:“TypeError: Cannot read property 'catch' of undefined”
    【解决方案2】:

    我建议你要么使用 Promise,要么使用 async/await

    有了承诺,您的示例将如下所示:

    function mainThread() {
      myFunction("Some data")
      .catch(function(error) {
        console.log("Error is ", error);
      });
    }
    
    function myFunction(param1) {
      return new Promise(function(resolve, reject) {
        asyncThirdpartyfunction(param1, function(err) {
          if (err) {
            reject(err);
          }
          resolve();
        });
      });
    }
    
    function asyncThirdpartyfunction(param, callback) {
      setTimeout(() => callback("Error"));
    }
    
    mainThread()

    在这里,我们或多或少地将第三方函数“转换”为Promise

    你也可以使用async/await,看起来像:

    async function mainThread() {
      try {
        const result = await myFunction("some data");
      } catch (error) {
        console.log("Error is ", error);
      }
    }
    
    async function myFunction(param1) {
      return new Promise(function(resolve, reject) {
        asyncThirdpartyfunction(param1, function(err) {
          if (err) {
            reject(err);
          }
          resolve();
        });
      });
    }
    
    function asyncThirdpartyfunction(param, callback) {
      setTimeout(() => callback("Error"));
    }
    
    mainThread()

    【讨论】:

    • 非常感谢您的回答。我写作为你的例子,但我想做的不同是“抛出”错误而不是“登录控制台”。目前,当它在控制台中抛出捕获时,它说:“未处理的 Promise 拒绝”。我需要抛出而不是记录,因为背后有一个生态系统来处理错误并做很多事情。我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多