Synchronous and asynchronous (promise,async,await)

(promise,async,await), macro task, micro task

1. Synchronous and asynchronous

Synchronization means that the code is executed within one frame; Asynchrony refers to waiting for a content to complete before execution.

console.log("aaa");
 for(var i=0;i<1000000000;i++){
 }
console.log("bbb");//synchronization

The synchronization stops, waits for the end of the operation, and continues the subsequent operation.

console.log("aa");
setTimeout(function(){
console.log("bb");
},5000)
console.log("cc"); //asynchronous

Asynchronous operation is to wait for one content to complete and then continue to execute the following content. However, the following content cannot be written outside the waiting function, otherwise two will be executed at the same time.

Common asynchronous events:

load event, setTimeout, setInteral, requestAnimationFrame()

If you use a lot of onload and onclick code, it is easy to cause callback hell. promise can be used at this point.

2,promise

Handle the asynchronous mode and spread the asynchronous mode for processing.

var p=new Promise(function(resolve,reject){
var img=new Image();
img.src="./img/17.jpg";
img.onload=function(){
resolve(img);
}
img.onerror=function(){
reject(img.src+"Address error");
}
})
p.then(function(a){
 console.log(a);//Execute resolve to execute this function
},function(b){
console.log(b);//Execute reject to execute this function
})

The function in promise has two parameters, both of which are functions. As shown in the above code, one is resolve, which is called when loading succeeds, and the other is reject, which is called when loading fails.

Promise has a then method, which also has two parameters. The first parameter is to execute the resolve function, and the second parameter is to execute the reject function.

p.then(function(a){
 console.log(a);//Execute resolve to execute this function
}).catch(function(b){
console.log(b);//Execute reject to execute this function
})

You can also use then in the same way as catch. In the function called by then, you can also use the return value of the function return to call then again

 new Promise(function (resolve, reject) {
        var img1 = new Image();
        img1.src = "./img/3-.jpg";
        img1.onload = function () {
          resolve(img1);
        };
      })
        .then(function (img) {
          arr.push(img);
          return new Promise(function (resolve, reject) {
            var img2 = new Image();
            img2.src = "./img/4-.jpg";
            img2.onload = function () {
              resolve(img2);
            };
          });
        })
        .then(function (img) {
            arr.push(img);
          return new Promise(function (resolve, reject) {
            var img3 = new Image();
            img3.src = "./img/5-.jpg";
            img3.onload = function () {
              resolve(img3);
            };
          });
        });

Promise provides an all method, which can uniformly process all arrays and return a list.

Promise.all(arr).then(function(list){
list.forEach(item=>{
console.log(item.src);
})

Promise also has a race method

 Promise.race(arr).then(function(img){
          console.log(img);//The asynchronous list executes whoever completes first

Can Promise continue then

var p=new Promise(function(resolve,reject){
resolve(1);
});
p.then(function(a){
 console.log(a);//  If there is no return Promise object here, it will continue to execute the content in the next then
// The corresponding execution object in the next then is still the current promise object
});
p.then(function(){
}) 

Sequence of code execution

In the promise object method, the then and catch methods themselves are asynchronous

In the promise object, except that then and catch are asynchronous, others are synchronous

console.log("a");
    new Promise(function(resolve,reject){
        console.log("b");
        resolve(1);
        console.log("c");
     }).then(function(a){
        console.log("d");
     }).then(function(){
        console.log("e");
     }) 
     console.log("f"); 
//abcfde

Interference of resolve and reject execution in promise

Only one can be executed, which is exclusive

function getImage(src) {
 return new Promise(function (resolve, reject) {
          var img1 = new Image();
          img1.src = src;
          img1.onload = function () {
            resolve(img1);
            reject(img1.src+"Address error");
          };
        });
      }

Promise status is divided into three parts
pending readiness
resolved the status of the resolve d execution
rejected the status of executing reject

3. async and await

The async function returns a promise object after execution

await can only be written in async functions

await can only handle asynchronous waiting of promise objects

The content returned by using return in async function can be obtained through then

 function getImage(src) {
        return new Promise(function (resolve, reject) {
          var img1 = new Image();
          img1.src = src;
          img1.onload = function () {  
            resolve(img1);
          };
        });
      }
async function loadImages(){
            var arr=[];
            for(var i=3;i<30;i++){     await getImage("./img/"+i+"-.jpg").then(function(img){
                    arr.push(img);
               })

4. Macro task, micro task

Both asynchrony and synchronization complete the contents of the task column

Synchronization tasks are carried out one by one

Asynchronous tasks have fixed time and non fixed time

SetTimeout, setinterval, requestanimationframe and promise are fixed times

Loading files and pictures is a non fixed time

setTimeout setInterval is a macro task

Promise micro task

Macro task refers to moving the current task to the top of the next task column for execution

Micro task refers to moving the content of the current task to the lowest end of the current task column for execution

Promise.resolve().then(function(){
            setTimeout(function(){
                console.log("b");
            },0)
        })
        setTimeout(function(){
            Promise.resolve().then(function(){
                console.log("a");
            })
        },0)

The micro task in the macro task executes the macro task in the priority micro task;

Micro tasks in micro tasks take precedence over micro tasks

Understand the following code sequence

console.log(1);//1
      new Promise(function (res, rej) {
        console.log(2);//2
        res();
      })
        .then(function () {
          console.log(3);//5
          Promise.resolve().then(function () {
            console.log(5);//6
            setTimeout(function () {
              console.log(6);//15
              Promise.resolve().then(function () {
                console.log(7);//16
              });
              setTimeout(function () {
                console.log(8);//18
              }, 0);
            }, 0);
          });
        })
        .then(function () {
          console.log(4);//7
        });
      setTimeout(function () {
        console.log(9);//8
        new Promise(function (res) {
          res();
          console.log(10);//9
        }).then(function () {
          console.log(11);//10
        });
      });
      Promise.resolve().then(function () {
        setTimeout(function () {
          Promise.resolve().then(function () {
            console.log(12);//14
          });
          console.log(13);//13
        }, 0);
      });
      setTimeout(function () {
        setTimeout(function () {
          setTimeout(function () {
            Promise.resolve().then(function () {
              console.log(14);//20
            });
            console.log(15);//19
          }, 0);
          console.log(16);//17
        }, 0);
        console.log(17);//11
      }, 0);
      console.log(18);//3
      new Promise(function (res) {
        console.log(19);//4
        setTimeout(function () {
          console.log(20);//12
        }, 0);
      });

Tags: Javascript

Posted by Seamless on Mon, 23 May 2022 10:59:57 +0300