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.

  • 相关阅读:
    dart中Map类型详解
    洛谷P1582 倒水(二进制)
    maven依赖 临时转阿里云镜像
    java jdbc 连接数据库
    java 常用类
    java 异常处理
    java 对象 this static 封装
    java 面对对象 内存分析
    团队开发 git
    java 代码块
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12336479.html
Copyright © 2011-2022 走看看