简体   繁体   中英

Why does the Javascript EventLoop have different result?

Recently, I read an article about Javascript EventLoop. But when I put the code into Visual Studio Code for execution, there are some different result. I'm confused. Thanks for help!

Here is the code:

console.log('1');

// written as set1
setTimeout(function () {
    console.log('2');
    // written as set4
    setTimeout(function() {
        console.log('3');
    });
    // written as pro2
    new Promise(function (resolve) {
        console.log('4');
        resolve();
    }).then(function () {
        console.log('5')
    })
})

// written as pro1
new Promise(function (resolve) {
    console.log('6');
    resolve();
}).then(function () {
    console.log('7');
    // written as set3
    setTimeout(function() {
        console.log('8');
    });
})

// written as set2
setTimeout(function () {
    console.log('9');
    // written as pro3
    new Promise(function (resolve) {
        console.log('10');
        resolve();
    }).then(function () {
        console.log('11');
    })
})

The result could be one of the following:

1,6,7,2,4,9,10,8,5,11,3

1,6,7,2,4,9,10,5,11,8,3

Hi Nita and welcome to Stack Overflow.

The order of log appearance in a browser is determined from a requirement in the HTML5 standard to execute call backs for resolved (fulfilled) promises before executing any call backs for expired timers in the timer queue.

The ECMAScript specification itself makes no attempt to define the execution priority of promise jobs that execute call backs to then handlers after promise settlement, with respect to other asynchronous events in the host environment .

Answers to Promise.then Job execution order go into more detail and provide links to relevant standards.

So, for an HTML5 compliant browser, the order of logs will be

 1, 6, 7, 2, 4, 5, 9, 10, 11, 8, 3

because execution of then handler callbacks set up on a fulfilled promise take priority over timer call backs.

The HTML5 standard does not dictate the relative priorities of timer and promise callbacks in non-browser environments such as Node.js.

So discrepancies between the order of logs made to the console can be attributed to differences in the host environment.

The take home thought is setting up code to rely on the outcome of race conditions between timers and promise call backs is a somewhat brittle exercise - it relies on host environment implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM