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.

  • 相关阅读:
    《需求分析与系统设计》第二篇阅读体会
    《需求分析与系统设计》第一篇阅读体会
    《编写有效用例》第二篇阅读体会
    项目目标文档
    字符流
    字节流
    递归
    File类
    JDBC接口和工具类
    异常
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12336479.html
Copyright © 2011-2022 走看看