首页 文章

拒绝承诺未定义

提问于
浏览
0

我尝试下面的函数使用 co 和javascript promise测试, fulfill 会成功返回但 reject 没有,并且捕获错误未定义 . 并且流程无法继续 . 为什么?

错误:

> at GeneratorFunctionPrototype.next (native)
    at onFulfilled (/Users/../project/app/node_modules/co/index.js:65:19)
    at runMicrotasksCallback (node.js:337:7)
    at process._tickDomainCallback (node.js:381:11)

码:

domain.run(function() {

  var testPromise = function() {
    return new Promise(function (fulfill, reject){
      //reject('error');
      reject(new Error('message'));
    });
  };


co(function *() {
  var d = yield testPromise();
  console.log(d);
  res.send('fin');
}).catch(onerror);
function onerror(error) { console.error(error.stack); }

});
domain.on('error', function(error) { console.error(error); });

1 回答

  • 5

    捕获错误未定义

    不会 . 它会捕获错误 'error' ,即您拒绝的值 . 当然,它不是真正的 Error 而是一个字符串,因此它没有 .stack 属性 - 这就是它记录 undefined 的原因 . 通过执行修复代码

    reject(new Error('…'));
    

    另见Should a Promise.reject message be wrapped in Error?

    流量无法继续 . 为什么?

    好吧,因为你有一个错误,抛出exceptions确实有这种行为 . 您还需要在错误处理程序中发送响应!

    co(function *() {
      …
    }).catch(function onerror(error) {
      console.error(error.stack);
      res.send('err');
    });
    

    或者如果您打算在通话时继续流程,请将 .catch 处理程序放在那里:

    co(function *() {
      yield testPromise().then(function(d) {
        console.log(d);
      }).catch(function(error) {
        console.error(error.stack);
      });
      res.send('fin');
    });
    

    或者,将您的promise调用包装在try-catch中:

    co(function *() {
      try {
        var d = yield testPromise();
        console.log(d);
      } catch(error) {
        console.error(error.stack);
      }
      res.send('fin');
    });
    

相关问题