Need help with Promise Chaining

Appreciate some help on understanding promise chaining.

const somePromise = new Promise((res, rej) => {

  .then((result) => new Promise((res, rej) => res(99)))     //1
  .then((result) => console.log(result))    //2

// Output 99

From what I understand, the chaining works cos a promise is returned at //1, which enables the then() at //2 to work.

However, for the example below, when a promise is Not returned at //3, how does the chaining continue? Somehow it still works with output 10

  .then((res) => 10)      //3
  .then((res) => console.log(res))

Thank you in advance!

The then method automatically returns the promise. You don’t need to manually return the promise so that you can call “then” as many times as you want.

Promise.then() returns Promise, so wrapping return value into Promise in step //1 wasn’t necessary. Couple notes:

  1. In scenario when you’re immediately resolve value, you can simply use static .resolve() method:
const somePromise = Promise.resolve(100);
  1. .then() method receives value as an argument, it’s quite confusing (+ creates shadow in your example //1) to use res as parameter name - I wouldn’t suggest that
  .then((v) => v * 2) // Resolved value was passed here
  .then((v) => console.log(v)); // 200

Thanks all for the explanation.

Just to clarify a few points.

If the returned value (non-Promise) of the callback function is automatically wrapped in a Promise (as in //3 above), I would imagine the very simplified representation of the then() method would be something like:

function then(fn) {
<some other codes>
return Promise.resolve(fn())       // fn() == 10 in this case

With this, the next then()'s res variable will have the value of 10.
Now if that is correct, when a Promise (instead of value like 10) is returned in //1, shouldn’t // 2 should have output of ‘Promise {}’ instead of 99, based on the assumption below:

function then() {
<some other codes>
return Promise.resolve(new Promise((res, rej) => res(99))