This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging

Review the knowledge about Promise, its concept, how to use it, and what to note. The reference is still the ESCMAScript6 introduction es6.ruanyifeng.com/ written by Teacher Ruan Yifeng. The reason for writing it is that Promise is often used for asynchronous processing in projects, but I do not have a systematic understanding of it.

Promise object

concept

In short, Promise is a JS single-threaded asynchronous processing scheme, which is often used in interface requests to the back end. I believe that most front ends are familiar with this. ES6 uses promises to standardize.

state

Promise has three states, and has the characteristics of being undisturbed and not changing once the state has changed.

The three states are

  1. Pending on
  2. Fulfilled successfully
  3. Rejected has failed

Note that once executed, the Promise cannot be cancelled in the middle of the execution. If the callback function is not set, the Promise will throw an error internally, and in the pending state, there is no knowing where it will progress.

use

In the front-end use process, generally in the request will be used, some used to encapsulate the request, there are also used in the store, of course, is also to encapsulate the request. Roughly as follows

function getUserInfo(data) {
  return new Promise((resolve, reject) = > {
    // Interface method
    if(true) {
      resolve('Return parameter')}else {
      reject('Wrong message')
    }
  })
}
getUserInfo(data).then(res= > {
  console.log(res)
}).catch(res= > {
  console.log(res)
})

Copy the code

This is probably the most common way to use it, along with promise.all (), which I’ll write about later.

The following is an example of loading images asynchronously

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

The important thing here is to use the resolve and success callbacks for the promise. If you get the image path, use resolve to return the correct address, and if you don’t, return the wrong address.

Implementation process

In a PROMISE, it is generally from progress to success or failure. If the current callback address is a new promise, then the state of the current promise depends on the state of the current callback promise.

Such as:

const p1 = new Promise((resolve, reject) = > {
  setTimeout(() = > resolve('p1'), 3000)})const p2 = new Promise((resolve, reject) = > {
  setTimeout(() = > resolve(p1), 1000)
})
p2.then(result= > console.log(result,'result')) // p1 result
  .catch(error= > console.log(error,'error'))
Copy the code

In this example, p2 is a successful callback, and p1 is also a successful callback. This is clear from the second example

const p1 = new Promise((resolve, reject) = > {
  setTimeout(() = > reject(new Error('wrong')), 3000)})const p2 = new Promise((resolve, reject) = > {
  setTimeout(() = > resolve(p1), 1000)
})
p2.then(result= > console.log(result,'result'))
  .catch(error= > console.log(error,'error')) / / Error: wrong
Copy the code

Two comparisons, we can see this point clearly.

Then (), and the catch ()

Promise instances have THEN methods that are defined on the prototype object promise.prototype. Then method can be called chain, colloquial is to save grandpa, one after another.

Similarly, promise.prototype also has a catch. The previous one handles callbacks, and this one handles errors.

Two equivalent ways of writing it

/ / write one
const promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) { reject(e); }}); promise.catch(function(error) {
  console.log(error);
});

/ / write two
const promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});
// Comparing the two methods, we can see that the reject() method is equivalent to throwing an error.
Copy the code

And the Promise object’s errors are passed back until they are caught

finally

The finally() method is used to specify the action that will be performed regardless of the final state of the Promise object. This approach was introduced as a standard by ES2018. Relatively less used, finally can also work wonders under certain circumstances, depending on the business scenario.

all()

The promise.all () method is used to wrap multiple Promise instances into a new one.

This method, in NuxTJS do server-side rendering will be used more. And in a very special way. Pack it all together, and then return it all. There are two kinds of state: all is fulfilled, the state is fuifilled; If one is rejected, then the state is rejected.

Are all fulfilled

 const p1 = new Promise((resolve, reject) = > {
  resolve('p1');
})
.then(result= > result)
.catch(e= > e);

const p2 = new Promise((resolve, reject) = > {
  resolve('p2');
})
.then(result= > result)
.catch(e= > e);

Promise.all([p1, p2])
.then(result= > console.log(result,'then')) // ["p1", "p2"] "then"
.catch(e= > console.log(e,'catch'));
Copy the code

There is one rejected

const p1 = new Promise((resolve, reject) = > {
  resolve('p1');
})
.then(result= > result)
.catch(e= > e);

const p2 = new Promise((resolve, reject) = > {
  throw new Error('Error reported');
})
.then(result= > result)
.catch(e= > e);

Promise.all([p1, p2])
.then(result= > console.log(result,'then'))
.catch(e= > console.log(e,'catch'));
Copy the code

Let’s look at the following example

const p1 = new Promise((resolve, reject) = > {
  resolve('p1');
})
.then(result= > result)
.catch(e= > e);

const p2 = new Promise((resolve, reject) = > {
  throw new Error('Error reported');
})
.then(result= > result)
.catch(e= > e);

Promise.all([p1, p2])
.then(result= > console.log(result,'then')) 
.catch(e= > console.log(e,'catch'));
Copy the code

P2 goes into rejected first, but since p2 has its own catch method, it returns a new instance, which is what P2 refers to. When the instance is finished, it also becomes resolved, so P1 and P2 go to the THEN method.

race()

In contrast to all(), the return value of the Promise instance that changed first is passed to the callback function

const p1 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 1000.'p1')
})
.then(result= > result)
.catch(e= > e);

const p2 = new Promise((resolve, reject) = > {
  resolve('p2');
})
.then(result= > result)
.catch(e= > e);

Promise.race([p1, p2])
.then(result= > console.log(result,'then')) // p2 then
.catch(e= > console.log(e,'catch'));
Copy the code

If you remove the timer, you will see that p1 is always executed

allSettled()

The promise.allsettled () method takes a set of Promise instances as parameters, wrapped as a new Promise instance. The wrapping of the instance will not end until all of these parameter instances have returned results, whether fulfilled or rejected. This method returns an instance, which is always fulfilled, rather than rejected, and accepts an array of arguments.

const promises = [
  fetch('/api-1'),
  fetch('/api-2'),
  fetch('/api-3')];await Promise.allSettled(promises);
removeLoadingIndicator();
Copy the code

any()

This method takes a set of Promise instances as parameters and returns them wrapped as a new Promise instance.

Promise.any([
  fetch('https://v8.dev/').then(() = > 'home'),
  fetch('https://v8.dev/blog').then(() = > 'blog'),
  fetch('https://v8.dev/docs').then(() = > 'docs')
]).then((first) = > {  // If only one of the fetch() requests succeeds
  console.log(first);
}).catch((error) = > { // All three fetch() requests failed
  console.log(error);
});
Copy the code

The above is the review of all knowledge points, deficiencies pointed out, also please give advice!!

Related articles

Let, const reviewJuejin. Cn/post / 699147…

Beginner koA building projectJuejin. Cn/post / 698756…

Regular Expression SummaryJuejin. Cn/post / 698615…

Flex Layout SummaryJuejin. Cn/post / 698497…

Basic Usage of mongodbJuejin. Cn/post / 698364…

Vue3 Setup management background – project setupJuejin. Cn/post / 696802…

Factory patterns, constructor patterns, and prototype patternsJuejin. Cn/post / 695794…