Using Promise chain call to solve the problem of multiple asynchronous callbacks

  • 2021-07-12 04:24:50
  • OfStack

Introduction

The so-called Promise is simply a container, which holds the result of an event (usually an asynchronous operation) that will end in the future.

Without scene support, it is difficult for novices to understand the meaning of Promise.

In "JavaScript You Don't Know", there is a scene that is very vivid:

I went to the counter of a fast food restaurant and ordered a cheeseburger. I gave $1.47 to the cashier. By placing an order and paying, I have made a request for a certain value (that is, the hamburger). I have already started a transaction.

But usually I can't get this burger right away. The cashier will give me something to replace the hamburger: a receipt with the order number. The order number is an IOU (I owe you, which I owe you) promise (promise) that I will get my hamburger eventually.

So I have to keep my receipt and order number well. I know this represents my future burger, so don't worry, but I am still hungry now!

While I'm waiting, I can do something else, like text a friend: "Hey, are you coming to lunch with me? I'm going to have a cheeseburger."

I'm already thinking about the cheeseburger of the future, even though I haven't got it yet. My brain can do this because it already uses the order number as a placeholder for cheeseburgers. Essentially, this placeholder makes this value no longer time dependent. This is a future value.

Finally, I heard the waiter shouting "Order 113", and then happily walked to the counter with the receipt, handed it to the cashier, and exchanged it for my cheeseburger.

In other words, once the value I need is ready, I exchange my promised value (value-promise) for the value itself.

However, there may be another result. They called my order number, but when I went to get the cheeseburger, the cashier apologetically told me, "Sorry, the cheeseburger is sold out." In addition to being angry about this situation as a customer, we can also see an important characteristic of future value: it may succeed or fail.

Every time I order a cheeseburger, I know that I will either get a cheeseburger or get the bad news that a hamburger is sold out, so I have to find something else for lunch.

Therefore, the emergence of Promise is actually a solution for asynchronous programming. It is more reasonable and powerful than traditional solutions-callback functions and events.

Basic Usage of Promise


var p1 = new Promise((resolve, reject) => {
 setTimeout(resolve, 1000, 'done');
 })
p1.then(data=>{
 console.log(data); // done
})

The obvious benefit of Promise1 is that it can be used to solve callback hell. Especially when dealing with multiple callbacks that depend on each other.

Resolving multiple asynchronous dependent calls using Promise

Promise provides one method Promise.all([p1,p2,p3]) For wrapping multiple Promise instances into a new Promise instance. The parameters received are an array, and p1, p2, and p3 are all Promise objects.

The state of Promise. all at this point depends on its parameters.

There are two situations:

When the states of p1, p2 and p3 are all resolve, Promise.all The state of will become resolve;; As long as one of p1, p2 and p3 has the status of reject, then Promise.all The state of will become reject;;

So we can use Promise.all() To resolve multiple asynchronous dependent calls.

For example, we often encounter a situation:

The website needs to get the user name first, and then get the user information according to the user name. Get the user name here getUserName() And get user information getUser() Are asynchronous requests that invoke the interface. Before getting user information, you need to get the user name. That is to say, getUser depends on the state of getUserName. So we can pass these two requests through Promise.all() Encapsulated as a new Promise object.


function getUserPromise(promiseX, promiseY){
 return Promise.all([promiseX, promiseY])
 .then(values =>
 //  Returned values By  promiseX  And  promiseY Gets or sets an array of values returned by the. 
  values
 )
}
function getUserName(){
 let data = 'superman';
 return new Promise((resolve, reject) => {
  setTimeout(resolve(data), 1000);
 })
}
function getUser(){
 let data = {
 id:1,
 username: 'superman',
 gender: 'male'
 }
 return new Promise((resolve, reject) => {
 setTimeout(resolve(data), 2000);
 })
}
getUserPromise(getUserName(), getUser())
.then(data => {
 //  Here's data Is to include getUserName  And  getUser An array of return values 
 console.log(data); // [ 'superman', { id: 1, username: 'superman', gender: 'male' } ]
 })

Chain calls using Promise


function getUserName(){
 let data = 'superman';
 return new Promise((resolve, reject) => {
 setTimeout(resolve(data), 4000);
 })
}
function getUser(username){
 let data = {
 id:1,
 username: 'superman',
 gender: 'male'
 }
 return new Promise((resolve, reject) => {
 if(username){
  setTimeout(resolve(data), 2000);
 }
 else{
  reject('err');
 }
 })
}
getUserName().then(username => {
 return getUser();
})
.then(user => {
 console.log(user);
})
.catch(err => {
 console.log(err);
})

With the chain call of Promise, it is no longer different to worry about callback hell.

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: