• A promise is simply a container that holds the result of some event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations.

Characteristics of a.

  • 1. The status of the object is not affected. The Promise object represents an asynchronous operation with three states: Pending,Resolved, and Rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state.
  • 2. Once the state changes, it will never change again. This result can be obtained at any time. There are only two possibilities for a Promise object to change state: from Pending to Resolved and from Pending to Rejected. As soon as these two states occur, the state is frozen and will never change, and the result will always be the same. If the change has already occurred, you can add a callback to the Promise object and get the same result immediately. This is quite different from an Event, which has the characteristic that if you miss it and listen again, you will not get the result.

2. Disadvantage

  • 1. Cannot cancel a Promise. Once a Promise is created, it will be executed immediately and cannot be cancelled midway
  • 2. If you don’t set a callback function, errors thrown inside a Promise won’t be reflected outside.
  • 3. When in a Pending state, there is no way to know the current stage of progress (just started or nearly completed)

Three. Basic usage

The Promise object is a constructor that generates a Promise instance

Let promise1 = new Promise((resolve, reject) => {console.log(' start '); resolve('success'); reject('error'); }); Promise1. then((value) => {console.log(value)}, (err) => {console.log(err)}) // Success is displayedCopy the code
Function timeout(ms) {return new Promise((resolve, reject) => {console.log(' start ') setTimeout(resolve, ms, 'done'); }); } timeout(1000).then((value) => { console.log(value); }); Done is printed 1000 milliseconds after the output startsCopy the code
  • The timeout method above returns a Promise and executes the resole method 1000 milliseconds later
Let p1 = new Promise((resolve, reject) => {console.log('p1 start execution '); setTimeout(() => reject(new Error('fail')), 3000); The console. The log (' p1 end? '); }) let p2 = new Promise((resolve, reject) => {console.log('p2 start execution '); setTimeout(() => resolve(p1), Then (data => {console.log(data)}). Catch (error => {console.log(error)}) P2 displays fail 3000 milliseconds after the start executionCopy the code
  • P2’s then method returns p1, an instance of promise, which executes p1 and rejects an error 3000 milliseconds later. P2’s catch method outputs the error

Iv.’ Bubbling ‘

Errors on Promise objects have the ‘bubbling’ nature of being passed backwards until they are caught, meaning they are always caught by the next catch statement

// bad
promise.then(data => {}, err => {});
// good
promise.then(data => {}).catch(error => {})
Copy the code
  • In face code, the second approach is superior to the first because it catches errors in the execution of the previous THEN method and is closer to the synchronous approach (try/catch). It is therefore recommended to use the catch method rather than the second argument to the then method.
  • Unlike a traditional try/catch block of code, if there is no callback that specifies error handling using the catch method, the error thrown by the Promise object is not passed to the outer code, that is, there is no response. However, Chrome does not comply with this rule and will throw an error “RfterenceError:”

Five. A few small methods

1) Promise.all() is used to wrap multiple Promise instances into a new Promise instance

let pall1 = new Promise((resolve, reject) => {
    resolve('resolve1');
    reject('reject1');
})
let pall2 = new Promise((resolve, reject) => {
    resolve('resolve2');
    reject('reject2');
})
let pall3 = new Promise((resolve, reject) => {
    resolve('resolve3');
    reject('reject3');
})
let p1 = Promise.all([pall1, pall2, pall3]);
Copy the code
  • In the code above, the promise. all method takes an array of parameters. Pall1,pall2, and pall3 are all instances of the Promise object.

The state of P1 is determined by P1, P2 and P3 and divided into two cases

  • The state of P1 will become fulFiled only when the states of PALL1, pall2, and pall3 become fulFiled. In this case, the return values of P1, P2, and P3 form an array and are passed to the callback function of fear
  • When one of pall1, pall2, and pall3 is rejected, the status of P1 becomes Rejected. In this case, the return value of the first rejected instance will be passed to the callback function of P1

2)Promise.race() wraps multiple Promise instances into a new Promise instance

let p = Promise.race([pall1, pall2, pall3]); // If an instance of PALL1, pall2, or pall3 is the first to change its state, the state of P will change accordingly. The return value of the Promise instance that changed first will be passed to the instance of P for further processingCopy the code

3) promise.resolve () transforms an existing object into a Promise object

  1. The promise. resolve parameter is a Promise instance, so promise. resolve will return the instance unchanged
  2. The argument is a Thenable object which is an object that has the then method
let thenable = { then: (resolve, reject) => { resolve(11); }} // The promise. resolve method converts this object to a Promise object, and then executes thenable's then method let pResoleve = promise.resolve (thenable); pResoleve.then(data => { console.log(data) })Copy the code
  • In the code above, when the thenable object’s then method executes,the pResolve state becomes resolved and the callback specified by the last then method executes 11 immediately
  1. Parameters are not objects with THEN methods, or are not objects at all
let p4 = Promise.resolve('hello');
p4.then(data => {
    console.log(data)
})
Copy the code
  • If the parameter is a raw value, or an object that does not have a then method, the promise.resolve method returns a new Promise object with the state Resolved
  • The code above generates a new instance of the Promise object, p4. Since the string is not an asynchronous operation, the return Promise state from lifetime achievement is Resolved, so the callback function will execute immediately, and the Promise. Resolve method parameter will be executed at the same time Pass to the callback function
  1. No arguments
  • The Promise. Resolve method allows you to call an Resolved Promise object with no arguments

4) Promise.reject()

  • The promise.reject () method also returns a new Promise instance with a state of Rejected

5) done()

  • p1.then().done()
  • The Promise method’s callback chain, whether ending in a then or catch method, might not catch if the last method threw an error. You can use the done() method, which is always at the end of the callback chain, to ensure that any errors that might occur are thrown

6)finally()

  • p2.then().done().finally()
  • The finally() method is used to specify actions that will be performed regardless of the final state of the Promise object. The biggest difference between the finally() method and the done method is that it takes as an argument a normal callback function that must be executed anyway