Considering code snippet below,
function one(){
var prm = new Promise(function(resolve,reject){
resolve("one");
});
prm.customKey = function(){
}
return prm;
}
function two(){
var prm = one();
prm.then(function(res){
return "two";
});
return prm;
}
function three(){
return one().then(function(res){
return "two";
});
}
I was hoping the below two would console res as "two" (resolve "two").
But strangely i) consoles res as "one", ii) consoles res as "two"
i) two().then(function(res){
console.log(res);
});
ii) three().then(function(res){
console.log(res);
});
Can someone explain why it is behaving like this.
then
in functiontwo
, you don't return there the promise returned by thatthen
call, but instead you ignore thatthen
return, and return instead the promise returned byone
, so obviously athen
on atwo()
will apply to the promise returned byone()
. Maybe you thought that a call tothen
would mutate the promise it was called on: this is not true. It returns a new promise without affecting the original promise.