The Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value. In ES6 syntax, a Promise is an object from which to get messages for asynchronous operations.

Promise objects have the following two characteristics:

  • The status of an object is not affected. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state.
  • Once the state changes, it never changes again, and you can get this result at any time. The state of the Promise object changes only in two cases: from pending to depressing and from pending to Rejected. As soon as these two conditions flourish, the state is frozen and will never change. If you add a callback to the Promise object, you’ll get the same result immediately. This is completely different from an event, which is characterized by the fact that if you miss it and listen again, you will not get the result.

eg1:

const promise = new Promise(function(resolve, reject) {
	// do something
    ifResolve (value)}else {
    	reject(error)
    }
})
Copy the code

The code above is an example of generating a Promise object. You can use the to specify the callback when you get resolved and Rejected.

promise.then(function(val){
	// success
}, function(error){
	// failure
})
Copy the code

Here is an example of an asynchronous method inside a Promise

function timeout (ms) {
  return new Promise((resolve, reject) = > {
  // The timer is executed periodically
  setTimeout(() = > {
      resolve('done')
    }, ms)
  })
}

timeout(1000).then(value= > {
  console.log(value)
})
Copy the code

Once a Promise is created, it executes immediately, but resolve is set to be thrown based on the internal calling method

let promise = new Promise((resolve, reject) = > {
	console.log('Promise')
    resolve()
})

promise.then(function() {
	console.log('resolved')})console.log('Hi! ')

// Promise
// Hi
// resolved
Copy the code

In the code above, as soon as a Promise is created, it executes and prints the Promise. Then is the callback function after resolve and will not be executed until the current script synchronization task is complete.

Promise loads the image asynchronously

function loadImageAsync(url) {
	return new Promise((resolve, reject) = > {
    	const image = new Image()
        image.src = url
        
        image.onload = function() {
        	resolve(image)
        }
        image.onerror = function() {
        	reject(new Error('Could not load image'))}}}Copy the code

Promise implements Ajax operations

const getJson = function(url) {
	const promise = new Promise((resolve, reject) = > {
    	let xhr = new XMLHttpRequest();
  		xhr.open('GET', url, true);
  		xhr.send();
        xhr.onreadystatechange = function () {
            // This step is to determine whether the server is responding correctly
          if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
            resolve(xhr.responseText)
          }
        }
    })
    
    return promise
}
getJson("/post.json").then(function(json) {
	console.log(json)
}, function(error) {
	console.log(error)
})
Copy the code

If resolve and reject are called with arguments, their arguments are passed to the callback function.

const p1 = new Promise((resolve, reject) = > {
	// ...
})
const p2 = new Promise((resolve, reject) = > {
	// ...
	resolve(p1)
})
Copy the code

In the code above, p1 and p2 are both instances of Promise, but P2’s resolve method takes P1 as an argument, meaning that the result of an asynchronous operation is the return of another asynchronous operation.

const p1 = new Promise(function (resolve, reject) {
  setTimeout(() = > {
      reject(console.log('---fail----'))},1000)})const p2 = new Promise(function (resolve, reject) {
  setTimeout(() = > {
      resolve(p1)
  }, 1000)
})

p2
  .then(result= > console.log(result))
  .catch(error= > console.log(error))
 
// ---fail----
Copy the code

Promise.prototype method

  • Promise.prototype.then()
// Then returns a new Promise instance
const promise = new Promise((resolve, reject) = > {
	setTimeout(() = > {
    	return resolve('chencc')},1000)
})

promise.then(resolve= > {
    console.log(resolve)
	return 'abc'
}).then(result= > {
	console.log(result)
})

// 'chencc'
// 'abc'
Copy the code
  • Promise.prototype.catch()
// Promise.prototype.catch() // .then(null, rejection) // .then(undefined, rejection) const promise = new Promise((resolve, reject) => { throw new Error('error') }) promise.then(val => { console.log('success') }).catch(err => { console.log('rejected: ' + err) }) // rejected Error: Then (val => {console.log('success')}). Then (null, err => {console.log('rejected ': '+ err)}) // EquivalentCopy the code

Internal Promise errors do not affect the external code of the Promise; in layman’s terms, promises eat errors.

const someAsyncThing = function() { return new Promise(function(resolve, Resolve (x + 2)})} someAsyncThing(). Then (function() {console.log('everything is great') }).catch(err => { console.log(err) }) setTimeout(() => {console.log(123)}, 2000 // ReferenceError: X is not defined / / 123 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / change the order of execution will have different results someAsyncThing (). The catch (err = > { console.log(err) }).then(function() { console.log('everything is great') }) setTimeout(() => {console.log(123)}, 2000) // ReferenceError: x is not defined // everything is great // 123Copy the code
  • Prmoise.prototype.finally()
Promise.then (result => {}).catch(error => {}).finally(() => {})Copy the code

Method on the Promise constructor

  • Promise.all()
const promise = Promise.all([p1, p2, p3])
Copy the code

The state of the promise is determined by P1, P2, p3

1) Only when P1, P2, and P3 become a big pity, the state of P will become a big pity. The return values of P1, P2, and p3 form an array and are passed to the callback of P.

Reject (p1, p2, p3); reject (p1, P2, p3); reject (P1, P2, p3);

  • Promise.race()
const promise = Promise.race([p1, p2, p3])
Copy the code

If one of the states p1, P2, p3 changes first, then the state of P changes. The return value of the first changed Promise instance is passed to p’s callback.

  • Promise.allSettled()
const promise = [
	fetch('/api1'),
    fetch('/api2'),
    fetch('/api3')
]

await Promise.allSettled(promise)
removeLoadingIndicator()
Copy the code

The following method is called to remove loading, no matter whether the loading succeeds or fails.

  • Promise.any()

A group of Promise instances will be accepted as parameters. As long as one of the Promise instances becomes fulfilled, the packaging instance will become fulfilled. If all the parameter instances become fulfilled, the packaging instance will become Fulfilled

  • Promise.resolve()
const promise = Promise.resolve($.ajax('/a.json'))
Copy the code

Transform an existing object into a Promise object

Promise.resolve('foo')

new Promise(resolve => resolve('foo'))
Copy the code
  • Promise.reject()
const promise = Promise.reject('error')

const promise = new Promise((resolve, reject) => {
	reject('error')
})
Copy the code

For the specific implementation of the Promise, we will write a handwritten Promise in a series of handwritten types.