How promises and promise chaining works? [Problem with code]

When you have one Promise, you can chain any number of Promises onto its .then. For example

const p = Promise.resolve();
p.then(() => console.log('then 1');
p.then(() => console.log('then 2');

means that p has two Promises that branch from it when it resolves: 1 and 2 (in addition to the promise p itself).

  p
 / \
/   \
1   2

What you're doing in your first code

let p = new Promise((resolve, reject) => {
  resolve("Hello world")
});
p.then(data => {
  console.log("second");
}).then(data => {
  console.log("third")
})
return p;

is like

"Hello world" = <Promise you return>
    |
    |
    |
  second
    |
    |
    |
  third = <unused Promise expression that the then chain resolves to>

You have two branches: the Promise you're returning resolves when Hello world runs, not when third runs.

On the other hand, when you call .then multiple times on a Promise, the whole expression evaluates to the Promise that resolves when the final .then runs:

let p = new Promise((resolve, reject) => {
  resolve("Hello world")
}).then(data => {
  console.log("Hello world a second time!");
}).then(data => {
  console.log("Hello world a third time")
})

return p;

is like

"Hello world"
     |
     |
'Hello second'
     |
     |
'Hello third' = <Promise you return>

where the returned Promise is the one that resolves right after Hello third runs.


Instead of returning p in the segregated version... return the p.then() chain. The final one will be added to the end of that chain, rather than creating two different chains

then() returns a new promise resolved by any return or undefined if no return

const query = () => {
  let p = new Promise((resolve, reject) => {
    resolve("Hello world")
  });

  return p.then(data => {
    // from `resolve()`
    console.log('Then 1: ', data)
    // return to next then()
    return ("Hello world a second time!");
  }).then(data => {
    // from previous then()
    console.log('Then 2: ', data)
    // return to next then()
    return ("Hello world a third time")
  });
}


query().then(res => console.log('Final: ', res))