0

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.

1
  • 3
    Well, despite the then in function two, you don't return there the promise returned by that then call, but instead you ignore that then return, and return instead the promise returned by one, so obviously a then on a two() will apply to the promise returned by one(). Maybe you thought that a call to then would mutate the promise it was called on: this is not true. It returns a new promise without affecting the original promise. Commented Oct 3, 2018 at 6:35

4 Answers 4

2

Because you return prm. That's a promise, that returns one. The place, where you return "two", this return statement is for the function it's called in, that means for the callback inside .then statement.

It doesn't affect the promise itself. You just used a promise (from one()) inside your two() method, and returned it as is.

Sign up to request clarification or add additional context in comments.

Comments

0

In second and third function you should also return new Promise that waits for another Promises and resolves its response, something like this:

function two(){
   return new Promise((resolve,reject) => {
      one().then(() => resolve("two"));
   });
}

Comments

0

In function two, prm variable wasn't actually updated when it was returned by the function.

after this line directly var prm = one();

it jumps to this line return prm;

because it is not expecting to get the data right now from the promise.

However, in the other function three you return the promise, so the result pops out as you are expecting.

For two to get the same results as three, add async and await

async function two(){
    var prm = one();
    await prm.then(function(res){
        prm = "two";
    });
    return prm;
}

Comments

-1

Try modifying function to this:

function two(){
  var prm = one();
  prm.then(function(res){
    return "two";
 });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.