What is synchronization?

Both synchronization and asynchrony are message mechanisms. In synchronization, A calls B, and B processes the result and then returns it to A. A waits for the result from B. Before receiving the result, A needs to wait and confirm whether the result is returned before continuing to perform the next step

What is asynchrony

A calls B without waiting for the result of B. B processes the call through the status or callback function. When the call result returns, the caller will be notified in the form of A message or callback

What are asynchronous requests?

Events, timers, network requests

Here are three ways to handle asynchronous requests: callbacks, Promises, and async, using an animation implementation as an example to illustrate the differences.

The callback function

<body> <div class="box"></div> <script> let box = document.querySelector('.box') function move(el,attr,val,cb){ let now = parseFloat(getComputedStyle(el)[attr]) let speed = (val - now)/Math.abs(val - now) clearInterval(el.timer) el.timer = setInterval(() => { if(Math.abs(val - now)<=0){ clearInterval(el.timer) cb && cb() } else { now+= speed el.style[attr] =  now+'px' } }, 10); } function moveBox(){ move(box,'left',100,function(){ move(box,'top',100,function(){ move(box,'left',0,function(){ move(box,'top',0,function(){ moveBox() }) }) }) }) } moveBox() </script> </body>Copy the code

In the above code, after the execution of an animation, the callback function is used to continue the next animation. There are as many callback functions as there are animations. This is callback hell

The callback hell

In the beginning, we used callback to handle asynchronous notifications. However, with too many callbacks, the structure of the code will inevitably have too many nested levels, resulting in a sharp decrease in readability and maintainability. This is callback hell

Promise

Promise doesn’t address asynchrony, it addresses the optimization of asynchronous writing

The last animation, which could have been written using the chain operation of the promise.then method, looked clearer

let box = document.querySelector('.box') function move(el,attr,val){ console.log('move',attr,val) let now = parseFloat(getComputedStyle(el)[attr]) let speed = (val - now)/Math.abs(val - now) return new Promise((resolve)=>{ clearInterval(el.timer) el.timer = setInterval(() => { if(Math.abs(val - now)<=0){ clearInterval(el.timer) resolve() } else { now+= speed el.style[attr] = now+'px' } }, 10) }); } function moveBox(){ move(box,'left',200).then(()=>{ return move(box,'top',200) }).then(()=>{ return move(box,'left',0)  console.log('left 0 ') }).then(()=>{ console.log('top 0 ') return move(box,'top',0) }).then(()=>{ moveBox() }) }Copy the code

The then method of a Promise returns a Promise object. The new Promise object can perform three states:

1. Default: Return a resolve Promise object in a state

2. Return a non-Promise object, then return an Resolved object

3. When the then callback returns a Promise, the return value of the THEN returns that Promise

The ultimate asynchronous scheme async await

    let box = document.querySelector('.box')
    function move(el,attr,val){
      console.log('move',attr,val)
      let now = parseFloat(getComputedStyle(el)[attr])
      let speed = (val - now)/Math.abs(val - now)
      return new Promise((resolve)=>{
        clearInterval(el.timer)
        el.timer = setInterval(() => {
          if(Math.abs(val - now)<=0){
            clearInterval(el.timer)
            resolve()
          } else {
            now+= speed
            el.style[attr] = now+'px'
          }
        }, 10)
      });
    }
    async function moveBox(){
      await move(box,'left',200)
      await move(box,'top',200)
      await move(box,'left',0)
      await move(box,'top',0)
      moveBox()
    }
    
    moveBox()
Copy the code