Understand promise through callback

Time:2021-1-28

Understand promise through callback

We all know that promise appears to avoid callback hell. So let’s first have a deep understanding of the defects of callback

Callback

1. Lack of trust

2. Uncertainty

Example

var money = 30;
Order (money, function getorder (OrderID) {// order is a callback function of the third party to place an order
   OrderId & pay (orderId); // get the order number after calling the third party payment pay method to pay. 
})
//... synchronization code

Code interpretation:The above code is only a part of the general code, in which order is a third-party order placing method, which needs to carry a callback function to get the order number in the past. There are some trust and uncertainty problems, such as:

1. It is possible that the callback function getorder will never be called, so we will never get the order number to pay;
2. There may be a callback, but it has been recalled more than once, which leads us to pay repeatedly;
3. If the callback time is uncertain, it is possible to call back immediately, and then the next synchronization code will be executed after the callback. It is possible that the asynchronous code is called internally and called back again, and then the next synchronization code will be executed before the callback.
4. It is also possible that the third-party module that placed the order made an internal error, which made it impossible for us to catch the exception;

The above is just a part of the defect of callback, but in fact, when we don’t like a thing, there are always so many reasons. When we like a thing, there is no reason to find a bunch of reasons. Here are the reasons for promise.

Promise

1. Trustworthiness and willfulness
2. Certainty

Before solving the above problem of callback function, it is necessary to know some main methods of promise

1. New promise ()

Example

console.log(1);
let promise = new Promise(function PromiseBack(resolve,reject){
    resolve();
    resolve();
    reject();
    reject();
    console.log(2);
}).then(()=>{
    console.log(4);
},()=>{
    console.log(5);
})
console.log(3);
//The results are: 1, 2, 3, 4

Code interpretation:The above code reflects the following features of new promise:

1. Once the resolution (resolve or reject) is called once, the resolution callback or change resolution callback will not be called again.

2. The decision code is synchronous, but the success or failure of the decision callback code must be asynchronous, and the asynchronous implementation of promise is earlier than the call time of setTimeout, because the callback decision exists in the microtask queue of event loop.

2. Simultaneous execution of multiple promises: Promise.all ([ .. ])

Example

let promise1 = new Promise(function(resolve,reject){
    resolve(1);
});
let promise2 = new Promise(function(resolve,reject){
    resolve(2);
    // reject(3);
});
let promise3 = Promise.all([promise1,promise2]).then(function resolveBack(result){
    console.log (result); // the print result is: [1, 2]
},function rejectBack(result){
    console.log (result); // when the comment part of promise 2 is released and the non comment part is commented, the print result is: 3
})

Code interpretation:Promise.all Method the resolution of promise array is as follows:When all the projects are successful resolutions, the successful resolution callback resolveback will be called, and the resolution values of the project array will be returned to the values in the resolve in the form of an array in order; if even one of the failed resolutions is called, the failed resolution callback rejectback will be called, and only the failed resolution values in the project host will be returned in the order of an array return

3. Multi promise competition execution: Promise.race ([ .. ])

Example

let promise1 = new Promise(function(resolve,reject){
  setTimeout(function(){
    resolve(1);
  },100);
});
let promise2 = new Promise(function(resolve,reject){
  setTimeout(function(){
   //resolve(2);
    reject(3);
  },50);
});
let promise3 = Promise.race([promise1,promise2]).then(function resolveBack(result){
    console.log (result); // the print result is: 2
},function rejectBack(result){
    console.log (result); // when the comment part of promise 2 is released and the non comment part is commented, the print result is: 3
})

Code interpretation:Promise.race Method is different from all method. Its resolution for promise array is as follows:When one of the promise arrays succeeds, the successful resolution callback will be executed immediately. When one fails, the failed resolution callback will be executed immediatelyCompetition resolutionOne of its common application scenarios isAsynchronous request timeout processingThe code is as follows:
Example:

//Request (..) is an Ajax tool that supports promise
let promise1 = request( "http://some.url.1/");
let promise2 = function(second=1000){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      Reject ('request timeout ');
    },second)
  })
};
let promise3 = Promise.race([promise1,promise2(3000)])
.then(function resolveBack(result){
    console.log(result);
},function rejectBack(result){
    console.log (result); // when the request times out for 3 seconds, the resolution fails and an error message is printed. If the information here is processed uniformly, it is better to make the timeout value consistent with the error result returned by the asynchronous request
})

4. Promise error handling catch

Example

new Promise((resolve,reject)=>{
  console.log(a);
}).catch((err)=>{
  console.log (ERR); // print result: 33 [referenceerror: A is not defined]
})

Code interpretation:Catch, like then, is promiseExample method, and it will be called after completionReturns a new promise instanceIn this way, we can continue then or catchChain flow of promise. In fact, the implementation of catch itself is similar to that of then, which can be regarded as that then has only failed resolution callbackthen(null,(err)=>{})。 That is to say, when the resolution code of “then” fails, even if the reject method is not called, the error will be caught

summary

After browsing the above methods, let’s solve the problem of the callback function we encountered at the beginning. The problem code is as follows:

Example

var money = 30;
let promise1 = new Promise(function(resolve,reject){
    order(money,function getOrder(orderId){ 
        orderId ? resolve(orderId) : reject(orderId);
    }); 
});
let promise2 = function(second=1000){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      Reject ('request timeout ');
    },second)
  })
};
let promise3 = Promise.race([promise1,promise2(3000)])
.then(function resolveBack(result){
    console.log(result);
},function rejectBack(result){
    console.log (result); // when the request times out or the internal code of order is wrong, the failed resolution will be called
})
//... synchronization code

Code interpretation:The promise example above shows how to avoid the callback problem

1. By using Promise.race The competition resolution method can locate the specific error code and cause if the third party’s order method does not call getorder;
2. According to promise’s resolution feature: once the resolution is not available, the status cannot be changed and cannot be repeated. It solves the problem of callback more than once;
3. According to promise’s decision callback is asynchronous, and the decision callback must be asynchronous, which solves the uncertainty of callback time.
4. According to the similar catch feature of rejectback, the failed resolution callback can catch the abnormal error report of the resolution code. In this way, if there is an internal problem in the third party, it can be caught.

Recommended Today

How to Build a Cybersecurity Career

Original text:How to Build a Cybersecurity Career How to build the cause of network security Normative guidelines for building a successful career in the field of information security fromDaniel miesslerstayinformation safetyCreated / updated: December 17, 2019 I’ve been doing itinformation safety(now many people call it network security) it’s been about 20 years, and I’ve spent […]