I'm so much confused about what happens behind the scenes when promise is produced and consume. Please clarify my points and sorry for my weak English.
- blank object is created with new keyword Promise constructor is called and new keyword set the this of Promise constructor points to the blank object this = blankobject.
- Promise constructor receives callback (executor function) in argument and calls the executor function.
- executor function receives two callbacks (resolve,reject) as arguments
- setTimeout gets called in the executor function and setTimeOut is async code
- async code goes to background and then Promise constructor returns Promise object formerly blank object and Promise object reference saved to myPromise.
- a variable is created
What happens next ? When then
method is called the code of then
method goes to background? I imagine it goes to background and a variable is console.log // 10
After main code execution finishes, async code start setTimeout
callback begins to execute and after execution finishes promise is fulfilled and resolved function returns value. How is this value stored in promise object and what happens in then
method ?
let myPromise = new Promise (
(resolve, reject) => {
setTimeout(() => {
console.log(getIDs)
resolve(10);
}, 1500);
}
)
let a = 10
myPromise.then(val => {
console.log(val);
})
console.log(a)
resolve(..)
, the callback function that you pass to.then(..)
is executed.myPromise
is just an instance ofPromise
. It will never be blank. As for goes to background, how that works depends on the JavaScript engine – Titus