preface

Record 11.26 met the Promise related questions, back then clearly know, because just wake up not ready really is the answer is too bad, merciless review Promise.

The body of the

The problem

  1. Promise.all()How does it work?
  2. Promis.reject(1).then(console.log).catch(console.log).then(console.log).catch(console.log)Run to where

reviewPromise(MDN)

1. PromiseWhat is the

Promise is used to indicate the final completion or failure of an asynchronous operation and its resulting value. Make asynchronous operations return values like synchronous methods: Asynchronous methods return a Promise. A promise has three states: Pending \ Rejected \ depressing

2. Chain call (then)

Perform two or more asynchronous operations in a row, starting the next operation after the success of the previous operation, with the result returned by the previous operation. The then() function returns a new Promise. When a Promise completes or fails, the function is called asynchronously

  • Returns a value, sothenThe returned Promise will become the accepted state, and the returned value will be used as the parameter value of the callback that accepts the state.
  • No value is returned, thenthenThe returned Promise will be the accepted state, and the accepted state callback will take the value ofundefined.
  • Throw an error, thenthenThe returned Promise will be the rejection state, and the thrown error will be the parameter value of the rejection state callback.

3. Some static methods

  • Promise.all()

    This method returns oneNew Promise object, in this objectAll of theThe promise object fires only if all of the promise objects succeed, or if any object failsimmediatelyFailure to fire that object, the new Promise object returns an array containing all of the promise return values,The orderConsistent with incoming; If the failed state is triggered, an error message is returned for the first promise object that triggered the failure.
  • Promise.race()

    When the incominganyImmediately after a child promise succeeds or fails, the parent promise invokes the child promise’s success or failure details as arguments, andreturnThe Promise object.
  • Promise.reject(reson)

    returnOne in the failed statePromise objectAnd passed to the corresponding processing method.
  • Promise.resolve(value)

    returnA state determined by a given valuePromise objectIf it is an object with a THEN method, the returned object is determined by the then method execution. ifThe value is null, returns a Promise object in the state of fulifle, and passes the value to the corresponding THEN method.

Answer the question!!

1. Promise.all(iterable)How does it work?

The promise.all () method passes in an iterable type of Promise (Array, Map, Set) and returns a Promise instance. The Promise’s resolve callback ends when all the Promise’s resolve callbacks are entered; Throw an error as soon as any incoming Promise’s Reject callback executes.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) = > {
      setTimeout(resolve, 100.'foo');
    });

Promise.all([promise1, promise2, promise3]).then((values) = > {
       console.log(values);
    });
// output: Array [3, 42, "foo"]
Copy the code

2.Promise.reject(1).then(console.log).catch(console.log).then(console.log).catch(console.log)

(I said to stop executing until the first then… I don’t know what I was thinking)

First understand what a catch() is! The catch method returns a Promise and handles rejection cases, which behave the same as then

Then analyze the topic:

  1. Let’s look at the results first
let p = Promise.reject(1).then(console.log('then1')).catch(console.log('catch1')).then(console.log('then2')).catch(console.log('catch2'))
console.log(p)
setTimeout(() = > {
    console.log(p);
})

/ / output
then1
catch1
then2
catch2
Promise { <pending> }
(node:54428) UnhandledPromiseRejectionWarning: 1
Promise { <rejected> 1 }
Copy the code

If the fulfillment or rejection of the Promise calling THEN changes and there is no callback to that state in then, then creates a new Promise object that is not processed by the callback. This new Promise simply accepts as its final state the final state of the original Promise that called the THEN.

  1. Start an analysis

    1. Reject (1) method, which returns a Promise object in a failed state

    2. .then(console.log(‘then1’)), the return Promise of the failed state calls the then() method, but there is no callback for that state, so create and return a Promise object with the same failed state as the original Promise

    3. Catch (console.log(‘catch1’)) is a failed Promise, but there is no callback for that state, so return a failed Promise and print catch1.

    4. Then (console.log(‘then2’)).catch(console.log(‘catch2’))

  2. Analysis of the key

    1. catchandthenThere’s not much difference in nature, but eventually a new Promise object is returned
    2. Also notice that the Promise state becomesfulfilledorrejectedYou can’t change the state after that

conclusion

Before, I only knew that the Promise state can not be changed after the pity or the rejected state. I didn’t pay attention to what should be returned by the then, catch and then() method if there is no callback function that handles the state.

In short, carefully read the document, do not just understand the surface!