抓住承诺拒绝

时间:2016-03-22 05:04:21

标签: javascript promise co

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

在我始终放过func() resolve之前,确定yield func()之后的返回结果,
如果我想指向onError()使用throw ..;

想知道任何更好的主意我可以func() reject但是yield func()之后定义,直接转到onError()

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

1 个答案:

答案 0 :(得分:1)

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

相关问题