Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Promises and setTimeout

I have been playing with Promises, but I am having trouble understanding what is happening with the following code:

function a() { 
    return new Promise(function (resolve, reject) { 
        resolve("hi from a!");
    });
}

function b() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from b!");
        }, 5000);
    });
}

function c() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from c!");
        }, 1000);
    });
}

a().then(function (resultFromA) {
    console.log("a() responded with: " + resultFromA);
    b();
}).then(function (resultFromB) { 
    console.log("b() responded with: " + resultFromB);
    c();
}).then(function (resultFromC) { 
    console.log("c() responded with: " + resultFromC);
});

I am expecting this to output a() responded with: hi from a! immediately, along with b() responded with: hi from b! and c() responded with: hi from c! after their respective setTimeout() fires. However, what I get this the following output immediately:

a() responded with: hi from a!

b() responded with: undefined

c() responded with: undefined

I was thinking that .then() waits on these promises, but it isn't. Any help would be appreciated.

like image 551
Brian Kieffer Avatar asked May 27 '26 18:05

Brian Kieffer


2 Answers

You need to return b() and return c() from within your then handlers.

then only "replaces" the first promise with a subsequent promise which is returned from its callback.

If your then callback doesn't return a promise, then the then applies to the original promise, and it will be executed immediately regardless of the contents/result of the previous then callback.

Basically...

a().then(function () {
  b()
}).then( # This "then" is chained off of a's promise

While conversely:

a().then(function () {
  return b()
}).then( # This "then" is chained off of b's promise
like image 108
meagar Avatar answered May 30 '26 08:05

meagar


You need to return promises to chain them :

a().then(function (resultFromA) {
  console.log("a() responded with: " + resultFromA);
  // return b() promise
  return b();
}).then(function (resultFromB) { 
  console.log("b() responded with: " + resultFromB);
  // return c() promise
  return c();
}).then(function (resultFromC) { 
  console.log("c() responded with: " + resultFromC);
});
like image 41
MacKentoch Avatar answered May 30 '26 08:05

MacKentoch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!