Promise vs setTimeout
Short answer Promises have better priority than setTimeout callback function in event loop stack(or how i understand it).
Long answer watch this video. Very helpful. Hope this helps.
https://www.youtube.com/watch?v=8aGhZQkoFbQ
Thanks @MickJuice for new and updated video for event loop.
https://www.youtube.com/watch?v=cCOL7MC4Pl0
What happens first: setTimeout 0 or await Promise.resolve?
Promise.resolve will schedule a microtask while setTimeout schedule a macrotask. And the microtasks will run before running the next macrotask.
More information about event loop in general: https://www.youtube.com/watch?v=8aGhZQkoFbQ
More technical details about events loop: https://www.youtube.com/watch?v=cCOL7MC4Pl0
What is difference between Promise, await/async, and setTimeout?
With setTimeout you just set a time in milliseconds that the procedure should wait until the callback function inside the setTimeout call is getting called.
Meaning:
setTimeout(() => {
console.log('Hello World!');
}, 1000);
When the setTimeout is getting executed, it will wait 1000 milliseconds = 1 second until it performs the console.log(); action.
In case of error handling, you still need to handle your errors manually, but you're also able to resolve Promises in the setTimeout.
So you could tell the program that it should wait 1 second until it resolves the Promise and it can catch exceptions as you said with the .catch() on the Promise call.
TL;DR: Async methods just wait until the method is done (if you await them) and setTimeout executes a code block after a given amount of milliseconds.
Promises vs function calls/setTimeOut
I am wondering if it is possible to just attach a promise to the first function and fire the second one when function A is done.
Promises work by hooking on the return values of functions. A function returns a promise which in turn you can hook on. JavaScript does not expose any way to detect when a function has finished executing. So for example if you have an API that does:
api.someAsyncThing(); // does not return a promise
There is no way to know when the function finished running unless it exposes a side effect in which case you can poll inside a setInterval and create a promise - that's very hacky though.
Also I am not sure what the main difference of the setTimeOut and the promise would be vs the first scenario.
setTimeout
introduces a timeout, it's quite possible that A will not finish within the timeout and B will start running before A is finished with nested callbacks. The only difference is that it might wait long enough - this is called a race-condition.
Why is a promise resolved before a setTimeout
Interesting question. In order to understand the reason, one needs to understand the JavaScript event loop.
.then()
queues a microtask. Microtasks are executed as soon as the JS call stack empties.
In this case (but not in all cases), setTimeout
queues a task in the main task queue. Tasks are queued for external events, timer handlers, rendering (in the browser), etc... If a task calls JS code, the next task will not run until all the microtasks associated with it finish running.
So here's what's happening:
- Task #1, queued internally by Node.js:
console.log(1)
logs1
. Output is1
setTimeout(() => { console.log(3) });
queues a task to log3
Promise.resolve().then(() => console.log(4))
queues a microtask to log4
console.log(7)
logs7
. Output is1 7
.- The JS stack empties, because there's no more statements. The microtasks begin to execute.
- Microtask #1-1, queued by
.then()
:- Logs
4
. Output is1 7 4
.
- Logs
- Microtask #1-1, queued by
- Task #2, queued by
setTimeout()
:- Logs
3
. Output is1 7 4 3
. - The JS stack empties, because there's no more statements, however there are no microtasks.
Final output:
- Logs
1
7
4
3
Execution order of Timeout and Promise functions(Main Tasks and Micro Tasks)
I think output one
and four
are pretty clear. setTimeout
is a part of Main Task queue while Promise
is of Micro task queue that's why "three" and finally "two" is printed.
Step by Step execution is as below:
When script is executed, console.log(“one”) is executed first.
When
setTimeout(…)
is encountered, runtime initiates a timer, and after 0ms. Callbackfunction() {}
ofsetTimeout(…)
is queued in Task queue.When promise object is encountered, its callback i.e
function() {}
is queued in Micro task queue.Finally, it executes last
console.log(“four”)
.
According to standard specification
Once a call stack is emptied, it will check Micro task queue and finds callback
function() {}
of promise.Call stack will execute it (logs three).Once again, call stack is emptied after processing callbacks in Micro task queue. Finally, event loop picks up a new task from the Task queue i.e callback
function() {}
ofsetTimeout(…)
( logs two) execute it.
Visual Image
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
Promise.resolve().then(function() {
console.log('three');
})
console.log('four');
Related Topics
How to Calculate Md5 Hash of a File Using JavaScript
How to Change the Content of a <Textarea> with JavaScript
JavaScript Get Window X/Y Position for Scroll
Template String as Object Property Name
What's the Best Way to Break from Nested Loops in JavaScript
Using Address Instead of Longitude and Latitude with Google Maps API
JavaScript Drag and Drop for Touch Devices
What Does [Object Object] Mean? (Javascript)
How to Convert Dd/Mm/Yyyy String into JavaScript Date Object
Detecting When a Div's Height Changes Using Jquery
Anonymous Class Instance - Is It a Bad Idea
How to Convert Blob to File in JavaScript
Which Keycode for Escape Key with Jquery
Check for Special Characters in String