Subramanian Vignesh
Subramanian Vignesh

Reputation: 217

Resolving promise data

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.

Upvotes: 0

Views: 79

Answers (4)

Osama
Osama

Reputation: 3040

Try modifying function to this:

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

Upvotes: -1

HM107
HM107

Reputation: 1391

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;
}

Upvotes: 0

Madmadi
Madmadi

Reputation: 2140

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"));
   });
}

Upvotes: 0

Javid Asgarov
Javid Asgarov

Reputation: 1532

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.

Upvotes: 2

Related Questions