Promise VS Settimeout

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:

  1. Task #1, queued internally by Node.js:
    1. console.log(1) logs 1. Output is 1
    2. setTimeout(() => { console.log(3) }); queues a task to log 3
    3. Promise.resolve().then(() => console.log(4)) queues a microtask to log 4
    4. console.log(7) logs 7. Output is 1 7.
    5. The JS stack empties, because there's no more statements. The microtasks begin to execute.
      1. Microtask #1-1, queued by .then():
        1. Logs 4. Output is 1 7 4.
  2. Task #2, queued by setTimeout():
    1. Logs 3. Output is 1 7 4 3.
    2. The JS stack empties, because there's no more statements, however there are no microtasks.
      Final output:
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:

  1. When script is executed, console.log(“one”) is executed first.

  2. When setTimeout(…) is encountered, runtime initiates a timer, and after 0ms. Callback function() {} of setTimeout(…) is queued in Task queue.

  3. When promise object is encountered, its callback i.e function() {} is queued in Micro task queue.

  4. Finally, it executes last console.log(“four”) .

According to standard specification

  1. 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).

  2. 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() {} of setTimeout(…) ( logs two) execute it.


Visual Image

Visual Image

console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
Promise.resolve().then(function() {
console.log('three');
})
console.log('four');


Related Topics



Leave a reply



Submit