Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 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.

question from:https://stackoverflow.com/questions/65600938/microtask-executed-before-the-current-task-finishes

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...