Search code examples
javascriptpromisees6-promise

JS Promises: if a handler in a `then` block returns a value vs returning a resolved promise, does the `then` block handle it the same way?


Say I have a function that returns a resolved promise like this:

let a = () => {return new Promise(res => res(1))}

and then I then-ify it like this:

a()
.then(val => {return new Promise(res => res(1))})

Here the then contains a handler that returns a promise resolved with 1, so the then block returns a promise resolved with 1 as well. Is that right?

Then say instead we have this:

a()
.then(val => {return 1})

The handler returns 1 instead of returning a promise resolved with 1.

What I Want To Know: Does the then block return a promise resolved with 1 in both of these scenarios, even though one handler returned a resolved promise and the other just returned a value? In other words, does a then block deal with handlers that return promises resolved with a value the same way they deal with handlers that return the value itself?


Solution

  • All values returned from a then block are implicitly wrapped in a Promise.resolve, so returning Promise.resolve(1) is unnecessary.