简体   繁体   中英

how to chain javascript promises and errors

suppose:

function f() {
  return p1()
    .then(function(p1res) {
       console.log('p1 ok');
       return Promise.resolve(p1res);
    }, function(err) {
       console.log('p1 err '+err);
       return Promise.reject(err);

    }).then( ... proceed

are the statements

return Promise.resolve(p1res);

and

return Promise.reject(err);

needed?

Are the statements return Promise.resolve(p1res); and return Promise.reject(err); needed?

Yes, this or something equivalent is needed if you plan to chain additional then handlers from those handlers and therefore need to preserve ("pass through") the value and status of the promise. However, even if are you going to do that:

  1. Instead of return Promise.resolve(p1res); it would be simpler and equivalent to just say return p1res; .

  2. Instead of return Promise.reject(err); it would be simpler and equivalent to just say throw err; , to continue the promise on the error path with the "reason" err .

However, if your goal is merely to have a handler to log the status, you do not need to, and probably do not want to, chain subsequent handlers from there, since that will require you to go to extra trouble to ensure that the status reporting handlers return the value or re-throw the error for the benefit of the downstream handlers. Instead, you can put the status reporting handler on a separate "branch", and not worry about what they return or pass through:

function f() {
  let result = p1();

  result . then(
      function(p1res) { console.log('p1 ok'); }, 
      function(err)   { console.log('p1 err ', err); });

  result . then(
    ...proceed

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