从承诺中捕获拒绝 [英] catch reject from promise

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

问题描述

我想保留来自 func() reject 的错误,而不是直接选择 onError()

I want to hold the error from func() reject, not direct to onError() by choise,

之前我总是让func() resolve,并在yield func()后确定返回结果,
如果我想直接到 onError() 使用 throw ..;

Before I always let func() resolve, and determine return result after yield func(),
if I want to direct to onError() use throw ..;

想知道任何更好的主意我可以让 func() reject 但在 yield func() 之后决定,直接到 onError() 与否

Wondering any better idea I can just let func() reject but detemire after yield func() , direct to onError() or not

co(function* () {
  yield func();
  // if reject catch here, not direct to onError 


  yield func();
  // if reject don't catch here just direct to onError

}).then(function (response) {
  response = JSON.stringify(response);
  res.send(response);
}, function (err) {
  onError(err);
});


// ...
func: function() {
  return new Promise(function (resolve, reject){
    ...
    reject();
  });
},

推荐答案

co 支持 try/catch:

co(function* () {
  try{
      yield func();
  }
  catch {
     // if reject catch here, not direct to onError 
  }




  yield func();
  // if reject don't catch here just direct to onError

}).then(function (response) {
  response = JSON.stringify(response);
  res.send(response);
}, function (err) {
  onError(err);
});

查看文档:https://www.npmjs.com/package/co#examples

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

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