Chaining Javascript promises

后端 未结 3 1249
一整个雨季
一整个雨季 2020-12-17 05:23

I\'m trying to understand Promises from the MDN documentation. The first example demonstrates the then and catch methods:

// We def         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 06:09

    shouldn't the codes be equivalent

    They are.

    If so, then wouldn't that mean that the catch callback would be called only if the promise returned from p1.then, not the promise p1, resolved to rejected?

    Yes, exactly.

    However when p1 rejects, p2 will do so as well, because you did not pass an onRejected handler to the .then() call that would have intercepted it. The rejection just propagates down the chain.

    I played around in JSFiddle with the three approaches. All three work.

    They do, but they don't do the same.

    p1.then(onFulfilled, onRejected);
    

    This is what you usually will want to do.

    p1.then(onFulfilled); p1.catch(onRejected);
    

    This ends up with two different promises, one that will be resolved with the onFulfilled result or rejected, and one that will be fulfilled or resolved with the onRejected result.

    p1.then(onFulfilled).catch(onRejected);
    

    Thats's a different beast than the first, see When is .then(success, fail) considered an antipattern for promises?.

提交回复
热议问题