简体   繁体   中英

catch reject from promise

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM