从承诺中赶上拒绝

catch reject from promise

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

之前我总是让func()resolveyield func()后确定return结果,
如果我想定向到 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();
  });
},

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