zoukankan      html  css  js  c++  java
  • [Javascript] Introduction to Microtasks

    In Javascript, there are two types of event loops for async tasks.

    First one, is well known one, for example, setTimeout, http request, click event will goes into this category. We can call it "Task event loop".

    Second one, is called "Microtasks event loop", it is for Promise.

    The execution order is 

    Call stack --> Microtask queue --> Task event queue

    Let's have a look code snippet to better understand the order:

            setTimeout(() => {
                console.log('first setTimeout')
            });
    
            setTimeout(() => {
                console.log('second setTimeout')
            });
    
    
            // Microtasks
            Promise.resolve().then(() => {
    
                console.log('Promise first then() evaluated successfully');
    
                return Promise.resolve();
            })
            .then(() => {
    
                console.log('Promise second then() evaluated successfully');
    
                test = true;
    
            });
    
            console.log('Running ...');

    What's you guess the console log order?

    The correct order is:

    Running ...
    Promise first then() evaluated successfully
    Promise second then() evaluated successfully
    first setTimeout
    second setTimeout

    Even we put setTimeout before Promise code, but still it get executed after promise.

  • 相关阅读:
    软件工程实践总结
    2020软件工程第五次作业05
    软件工程问题清单
    2020软件工程第四次作业04
    用SQL*Plus命令启动和关闭数据库
    2020软件工程第三次作业03
    2020软件工程作业02
    图像处理问题清单
    2020软件工程作业01
    Markdown 快速入门
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12336479.html
Copyright © 2011-2022 走看看