简体   繁体   中英

In Javascript is setTimeout blocking when embedded in a group of promises?

I have a function func that is largely composed of a number of promises, five promises in all. In the third promise I have a very long setTimeout that could last as long as 3 days. If func is called more than once will it cue up additional requests and pass each one according to the setTimeout within the third promise or will it block other requests to the func ?

Bonus - is a set up like this likely to cause other unforeseen consequences?

setTimeout is not blocking. Calls to .then to chain callbacks for promises are blocking, but these should use up a tiny amount of CPU time. The answer to your question is that if you call func more than once, the function calls will effectively run in parallel even though they use setTimeout because it doesn't block.

Rather than just take my word for it, though, you can try running an example:

function run(timeout) {
    return new Promise(function (resolve) {
        setTimeout(resolve, timeout);
    });
}

run(10000).then(function () {
    console.log("10 second resolution");
});
run(3000).then(function () {
    console.log("3 second resolution");
});
run(1000).then(function () {
    console.log("1 second resolution");
});

This will print 1 , 3 , and 10 after approximately 1, 3, and 10 seconds, respectively, even though they were called in reverse order.

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