• [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.

  • 相关阅读:
    单点登陆的javascript类原创
    goole图标
    字符串string的相关应用
    今天心情好,发首我喜欢的歌天黑黑
    爱情幸福!
    linux虚拟实现
    页面显示的问题
    由我们MIS的老师,所引发的一点感想.
    有关PERL5和正则表达式
    本来没有什么好说的!
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12336479.html
Copyright © 2020-2023  润新知