拒绝未定义的承诺 [英] reject in promise undefined

查看:90
本文介绍了拒绝未定义的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried below function use co and javascript promise test, the fulfill will success return but reject not, and catch error undefined. and the flow can't continue. why?

错误:

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

推荐答案

捕获错误未定义

catch error undefined

不.它捕获错误'error',即您拒绝使用的值.当然,它实际上不是Error,而是字符串,因此它没有.stack属性-这就是为什么它记录undefined的原因.修正您的代码

No. It catches the error 'error', the value you rejected with. Of course, it's not really an Error but a string, and as such it does not have a .stack property - that's why it logs undefined. Fix your code by doing

reject(new Error('…'));

另请参见是否应将Promise.reject消息包装在错误中?

流程无法继续.为什么?

the flow can't continue. why?

好吧,因为您遇到了错误,并抛出了例外确实具有此行为.您还需要在错误处理程序中发送响应!

Well, because you've got an error, and thrown exceptions do have this behaviour. You'll also want to send a response in your error handler!

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

或者,如果您打算在呼叫中继续执行流程,请在此处放置.catch处理程序:

Or if you intend to continue the flow at the call, put the .catch handler right there:

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

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

Alternatively, wrap your promise call in a try-catch:

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

这篇关于拒绝未定义的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆