I am new to JS and was learning Promises. The confusion I faced is that callback in then() is pushed into job queue. Here is an example:
let promise = new Promise((resolve, reject) => {
resolve(setTimeout(()=>console.log('Done'),2000))
})
.then((data) => {
data;
})
So, we have promise which is resolved with console.log('Done'). After that, console.log('Done') is passed to then() and callback in then() is passed to job queue. Why? after we are given the data from asynchronous setTimeout, why need to pass callback in then() to job queue?
Edited
Say we have the following code:
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 2000);
})
.then((data) => {
console.log(`resolved value: ${data}`);
return 'bar';
})
Does the above code work like this. First, when the code is executed, JS engine encounters promise and setTimeout inside. Then, setTimeout is pushed into Web Api then JS engine continues executing the code and encounters then and its callback. Then then's callback is pushed into job queue and waits until promise is resolved. Is that correct?