confused with .then() in promises

Viewed 113

I'm new to js and I'm learning promises. I came up with this code which will print the resolved values from every function and will call new functions using .then


function login() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {

            resolve({username : 'default'})
        }, 1000)
    })
}

function getVideos() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(['vid1', 'vid2'])
        },1000)
    })
}

function getDesc() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {

            resolve('desc')
        }, 1000)
    })
}


const test = login()
test.then(res => {
    console.log(res)
    getVideos()
})
.then(res => {
    console.log(res)
    getDesc()
})
.then(res => console.log(res))

But, I'm not getting the expected result, I thought all the statements in .then() needed to be executed and resolved to continue to the next .then() statement. But clearly this is not the case here as I'm getting the following as the output -

{ username: 'default' }
undefined
undefined

But I expected the output to be similar to this -

{username : 'default}
['vid1', 'vid2']
desc

pls, point where I'm going wrong here. Any help is appreciated, thanks a lot

2 Answers

You need to add return to inside your chains when you're calling those functions. For example:

function login() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {

            resolve({username : 'default'})
        }, 1000)
    })
}

function getVideos() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(['vid1', 'vid2'])
        },1000)
    })
}

function getDesc() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {

            resolve('desc')
        }, 1000)
    })
}


const test = login()
test.then(res => {
    console.log(res)
    return getVideos()
})
.then(res => {
    console.log(res)
    return getDesc()
})
.then(res => console.log(res))

This is a good guide: https://javascript.info/promise-chaining

Make a couple of very minor changes:

const test = login()
test.then(res => {
  console.log(res)
  return getVideos()
})
.then(res => {
  console.log(res)
  return getDesc()
})
.then(res => console.log(res))

To chain promises together, you need to return the promises at each step. As it is you're implicitly returning undefined which is not a promise.

Related