JS ES6 Promise Chaining

后端 未结 5 2070
南笙
南笙 2020-12-10 14:28

I\'m trying to learn how to use promises, but am having trouble comprehending the chaining. I assume that with this code, both promises will run. Then when I call test.then(

5条回答
  •  庸人自扰
    2020-12-10 14:54

    Summary:

    The basic concept of promise chaining with promises is that every then / catch method on a fulfilled promise returns another promise. It works in the following manner:

    • When a promise is resolved the callback passed in the then method is called. The then method wraps the value which is returned in its callback in a resolved promise and returns this resolved promise.
    • When a promise is rejected the callback passed in the catch method is called. The catch method wraps the value which is returned in its callback in a rejected promise and returns this rejected promise.

    Example:

    Before fully understanding the concept of chaining multiple then methods it is important to know what exactly the return values of then and catch are. Take the following example:

    let prom1 = new Promise((res, rej) => {
      res('res');
    });
    
    const resolvedProm1 = prom1.then((val) => {return val});
    // setTimeout needed for the promise to actually be resolved
    setTimeout(() => console.log(resolvedProm1));
    
    let prom2 = new Promise((res, rej) => {
      rej('rej');
    });
    
    const resolvedProm2 = prom2.catch((err) => {throw err});
    // setTimeout needed for the promise to actually be rejected
    setTimeout(() => console.log(resolvedProm2));

    We can observe the status of the promises in the chrome devtools:

    What basically happens is that in a then or catch callback is the following:

    • Any value returned in a then or catch callback is wrapped in Promise.resolve() and a new resolved promise is returned.
    • Any error thrown in a then or catch callback is wrapped in Promise.reject() and a new rejected promise is returned.

    Because we are getting returned a rejected or resolved promise object we can repeat the cycle and call the then or catch method on it again. For example:

    const prom = new Promise((res, rej) => {
      if (Math.random() > 0.5) {
        res('success');
      } else {
        rej('error');
      }
    });
    
    prom.then((val) => {
      return val;
    }).then((val) => {
      return val
    }).then((val) => {
      console.log(val)
    }).catch((err) => {
      console.log('err');
    })

    This calling of then and catch methods which are executed in their respective order is called promise chaining. It is a very useful technique to make working with asynchronous code easier, especially if multiple asynchronous operations need to be performed which are dependend on each others data.

提交回复
热议问题