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?

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

Leave a Reply