Hey guys so I've been so confused hearing that the callback of a promise executed asynchronously I'm starting to get to a point where I'm not sure if I'm right or wrong.
From what I know the golden rule of Javascript is that it's single-threaded in other words Javascript executes code SYNCHRONOUSLY ONLY ! So now I will explain the way I understand how promises work and please tell me if I'm correct.
var p = new Promise((resolve)=>{resolve('Hello StackOverflow !');})
Ok, so the first that's happening is that we are creating a promise.
And basically, it runs the callback we passed as an argument, and the resolve is doing is three things!
1.it sets the [[PromiseState]] to fulfilled
it will set the [[PromiseValue]] to whatever value put in the resolve
it checks if we already created the callback from
then
and if we already made the callback it will push the callback to the Microtask and when the whole execution context will be popped off the stack the event loop will take place and the callback will run.p.then((cur)=>{console.log(cur);})
Now then
is running and what it does is 2 things
1.it will save the callback we made somewhere so the resolve function will have access to the callback
- it will check if [[PromiseState]] is no longer pending and if it's no longer in pending state it will push the callback into the Microtask and once again after the whole execution context will be popped off the stack the event loop will take place and the callback will run
Here I've made a mini promise function of my own it doesn't contain all the features like reject
finally
catch
but it's enough to get a basic idea.
(function(){
const PENDING = 'Pending', FULFILLED = 'Fulfilled';
var Promise = function(executor){
this.status = PENDING;
this.callback = null;
this.value = null;
var resolve = (value)=>{
this.value = value;
this.status = FULFILLED;
runCallBackIF.call(this);
};
executor(resolve);
};
Promise.prototype.then = function(fn){
this.callback = fn;
runCallBackIF.call(this);
};
var runCallBackIF = function(){
if(typeof this.callback === 'function'){
if(this.status === FULFILLED){
queueMicrotask(()=>{this.callback(this.value)});
}
}
};
window.Promise = Promise;
})();
var p = new Promise(function(resolve){resolve('Hello Stackoverflow !')});
p.then(function(cur){
console.log(cur);
});
So, am I right or completely wrong and Javascript promises absolutely don't work that way
I hope to hear it from you because I get so confused when people say that the promises callback executes asynchronously.