javascript - Meteor:如何捕获异步回调函数错误

标签 javascript asynchronous meteor asynccallback

我正在 try catch 可能在异步函数中引发的错误。

我尝试使用 Fiber 包,但安装此包后,应用程序不会开始出现此错误:

=> Errors prevented startup:

While building the application:

node_modules/fibers/build.js:1:15: Unexpected token ILLEGAL

所以我放弃了这个包(这也意味着 Future 类)...

我还尝试使用 Meteor.wrapAsync 包装回调函数,但这也不起作用。

这是我正在使用的代码:

try {
    Meteor.users.update({
        _id: this.user_id
    },{
        $set: {first_name: "test"}
    },{
        multi: false
    }, function(error, response){
        if(response < 1)
            throw "user could not be updated!";
    });

    console.log('user updated');
}
catch(error) {
    console.log('catched');
    console.error(error);
}

由于回调函数是异步的,因此它不会被捕获,因为抛出错误时 catch block 代码已经运行。我只是想找出一种方法来捕获我抛出的错误。

最佳答案

在服务器上,collection.update已经可以同步使用。所以你需要做的就是:

try {
  var documentsAffected = Meteor.users.update({
      _id: this.user_id
  },{
      $set: {first_name: "test"}
  },{
      multi: false
  });

  if (documentsAffected < 1) {
    throw new Error("user could not be updated!");
  }

  console.log("user updated");

} catch (error) {
  // will also catch exceptions thrown by Meteor.users.update
  console.log("caught an error!");
  console.error(error);
}

关于javascript - Meteor:如何捕获异步回调函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232757/

相关文章:

javascript - 我将如何在 Babylonjs 中使用线条绘制方框区域?

c# - 如何关闭未实现 IDisposable 的单例服务

c# - 带等待的命名互斥量

javascript - 将空格键参数传递给另一个空格键参数

JavaScript 表单验证,确保出生日期为 4 位数字

javascript - CSS 将文本置于图像之上

javascript - Node : Waterline + Caolan/Async: bind function

javascript - Meteor accounts-google Token 过期

javascript - Meteor 的 Accounts.onEmailVerificationLink 与 React 和 React Router

javascript - 我的代码在 Meteor 中不能正常工作,但可以在 JS fiddle 上工作