catch reject from promise

霸气de小男生 提交于 2019-12-20 06:13:26

问题


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

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

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

回答1:


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

See docs : https://www.npmjs.com/package/co#examples



来源:https://stackoverflow.com/questions/36146468/catch-reject-from-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!