Callback hell (callback) and promise and encapsulate setTimeout into promise

Callback and Promise, encapsulate setTimeout into Promise

  • Why does Callback hell happen?
  • What kind of veil does Promise wear?

First of all, the emergence of Promise is to rescue all the people trapped in the Callback hell. I believe that the callback hell is one of the most troublesome problems for JavaScript developers! Especially when I took over the code of the predecessors, I opened it and saw the callback nesting full, do I really want to hand out the resignation letter; then how does the Promise save all the people in pain?

table of Contents

1. The order of callback functions and callback hell

2. Timer

3. Network request

4.Promise

5.sleep function

The order of callback functions and callback hell

Our example of Naruto (I believe most of you have seen it): If you are Kakashi, when there are too many enemies, you will open the writing wheel. After the writing wheel is opened, you need to use Chidori and Chidori before you burp. After the bird runs out, you must pay attention to the shadow clone;

The following is expressed in pseudo code:

卡卡西.addEventListener('敌人太多', function(){
    
    
  卡卡西.addEventListener('快嗝屁了',function(){
    
    
    写轮眼();
    卡卡西.addEventListener('写轮眼开完了',function(){
    
    
      跑路();
    })
  })
})

The above example is a common callback hell, which is why many people often do it when they deal with too many things in the office and don't know what they are doing.

In order not to overly nest too many registration events and callback functions, developers later thought of various patterns, and finally the promise was incorporated into the ES6 standard;

Timer

Timer is a very common method in JavaScript, and its syntax is quite similar to the previous registration event

var timeoutID = scope.setTimeout(code[, delay]);

The first parameter is the callback function (Callback) mentioned above, and the second parameter is the number of microseconds;

As an example:

Suppose your roommate is a fat house who likes to operate many sessions at the same time. One day this fat house said to you: "Hey, help me turn on the computer in ten minutes. I want to go back, please!"

setTimeout(() => 开电脑, 10*60*1000)

The built-in timer will trigger this event after ten minutes;

Note:clearSetTimeout(timerId) You can stop the timer event

Usually this fat house will not let you go so easily, he will also say to you: "Help me connect to Steam two minutes after opening, and then help me with the next game."

setTimeout(()=>{
    
    
 打开电脑();
 you.addEventListener('opened',()=>{
    
    
  setTimeout(()=>{
    
    
    连上steam();
  },2*60*1000)
 })
},10*60*1000)

Network request

In JavaScript, we don’t want an operation to take too long, just like if it takes ten minutes for a customer to order a meal, the waiter cannot serve other guests during this time. Therefore, many long-term operations, such as IO and network requests, generally use asynchronous processing.

There are two main types of network requests: XMLHTTPRequest (the famous ajax is encapsulated for this), and later fetch. XHR mainly registers loadevents for the requested event to monitor the response (response). The easiest way isaddEventListener

function reqListener () {
    
    
  console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

Later, the fetch standard used the chain call of the then method.

fetch('http://example.com/movies.json')
  .then(function(response) {
    
    
    return response.json();
  })
  .then(function(myJson) {
    
    
    console.log(myJson);
  });

This then is provided by the prototype of the promise, and fetch is the entity of the promise;

Promise

Insert picture description here

Promise (promise), promise may keep promise (resolve), promise failure (reject). Before the result of the Promise appears, it will enter a state (Pending) where you don't know whether it is a success or a failure.

Promise ->pending->(resolve/reject)

Fortunately, the Promise API is very friendly. You can use the two methods of then and catch to put the callback function in to process the two final structures;

function success(){
    
    
  // do something when success 
}
function fail(){
    
    
  // do something when fail
}
(Statement will pending)
  .then(success)
  .catch(fail)

Finally, whether it is then or catch, Callback will be Promise.

fetch('https://your-domain/api.json')
  .then(res=>res.json()) /* 这也是异步 */
  .then(j=>console.log(j.id)) /* json() resolve 之后 */
  .catch(()=>alert('fail'))

sleep function (encapsulate setTimeout)

Traditional setTimeout

setTimeout( ()=>{
    
    } , 1000)

We hope this can pause for a while and do some related operations, but we don’t want to write too nested callback functions

/* 最终希望的函数 sleep */
sleep(5).then(()=>console.log('5秒过去'))

Further modification

function sleep(sec){
    
    
 setTimeout(()=>{
    
    },sec*1000)
}

This should be the case initially, but the then method cannot be used without Promise

function sleep(sec){
    
    
 return new Promise((resolve,reject)=>{
    
    
  setTimeout(()=>resolve(),sec*1000)
 })

Before setTimeout is triggered, the sleep function will be in the pending state; but reject is still not useful, so a feature is added here, if it exceeds ten seconds, it will be rejected;

/* 想象中的sleep */
sleep(5).then(()=>{
    
    })
sleep(11).then(()=>{
    
    }).catch(e=>console.log(e)) // Error:睡太久了八?

Combining the above modifications is:

function sleep(sec){
    
    
 return new Promise((resolve,reject)=>{
    
    
  if(sec > 10) reject(new Error('睡太久了八!'));
  setTimeout(()=>resolve(),sec*1000)
 })
}
sleep(11).catch(e=>console.log(e)) // Error: 睡太久了八!

End

This article is a small record made when I encountered the knowledge point of promise when I was learning Vue;

Guess you like

Origin blog.csdn.net/qq_40240053/article/details/108765515