Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - MicroTask executed before the current task finishes

I have been lately reading about the differences between macro and micro tasks in JavaScript. I stumbled upon a thing I can't understand. In this article there is an example of promise usage in coditionals and how they can affect execution ordering. Here is a short snippet I did to reproduce it on my PC:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script>
        const root = document.getElementById("root");
        const cache = {};

        root.addEventListener("load", () => console.log("Loaded data"));

        function getData(url) {
            if (cache[url]) {
                root.dispatchEvent(new Event("load"));
            } else {
                Promise.resolve({a: 5}).then(data => {
                    cache[url] = data;
                    root.dispatchEvent(new Event("load"));
                });
            }
        }
    </script>
</body>
</html>

Having the above HTML page open in the browser pase the following code in the console two times.

console.log("Fetching data...");
getData("test");
console.log("Data fetched");

The result of this is the following:

Fetching data...
Data fetched
Loaded data
Fetching data...
Loaded data
Data fetched

I can't quite get why the order of the log statements is different the second time I execute the code. From what I understand micro/macro tasks can't be processed before the current script or task in this case (as far as I know every snippet of code is wrapped in a macrotask which is then processed by the event loop) finishes. I would expect the same order in all cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...