Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binding multiple callbacks for promises returns resolve value of first promise, not second

I have the following code as part of some coding practice I am doing:

var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve('hello world');
    }, 2000);
});

var promiseTwo = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('hello again!');
    }, 2000);
});

promise.then(promiseTwo).then((data) => {
    console.log(data)
})

When the data is logged, it reads hello world and not hello again!. Why is that? My thinking was that the line promise.then(promiseTwo).then((data) => { console.log(data) })
would resolve the first promise, then pass the second promise in as a callback which would resolve to hello again!. Why does the resolve in promiseTwo never get return from the .then method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you’re not returning promiseTwo in then, you’re simply calling it, try:

var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve('hello world');
    }, 2000);
});

var promiseTwo = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('hello again!');
    }, 2000);
});

promise.then(() => promiseTwo).then((data) => {
    console.log(data)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading