Why is promise resolving with undefined?

Viewed 22294

var firstPromise = new Promise((resolve, reject) => {
  resolve('first promise');
});

firstPromise.then(() => {
  return new Promise((resolve, reject) => {
    resolve('second promise');
  }).then((result) => {
    console.log('hello');
  });
}).then((result) => {
  console.log(result);
});

I know this is not the best way to write this promise chain, but I was wondering why the last .then executes at all. I'm not returning anything with console.log('hello'), so wouldn't the .then off of the second promise never resolve?

3 Answers

You can call any number of then s after the resolve of promise. in your case: //1 resolved promise assigned to //2 results //4 has no returns to work with. So, results are undefined.

var firstPromise = new Promise((resolve, reject) => {
    resolve('first promise');
});

firstPromise.then(() => {
    return new Promise((resolve, reject) => {
        resolve('second promise');//1
    }).then((result) => {
        console.log(result);//2
        console.log('hello');//3
    });
}).then((result) => {
    console.log(result);//4
}).then((result) => {
    console.log(result);
}).then((result) => {
    console.log(result);
}).then((result) => {
    console.log(result);
})

if you have return something after //3 result is assined by it.

var firstPromise = new Promise((resolve, reject) => {
    resolve('first promise');
});

firstPromise.then(() => {
    return new Promise((resolve, reject) => {
        resolve('second promise');//1
    }).then((result) => {
        console.log(result);//2
        console.log('hello');//3
        return("test")
    });
}).then((result) => {
    console.log(result);//4
}).then((result) => {
    console.log(result);
}).then((result) => {
    console.log(result);
}).then((result) => {
    console.log(result);
})

Related