0

I'm trying to better understand promises and async code in Javascript.

In doing so, I wrote the following, simple async function in the Chrome console:

const myAsync = async() => 10;

As expected, myAsync returns a promise, but when I call .then() (i.e. myAsync().then(res => res)), then console displays Promise{<fulfilled>: 10}. The promise is clearly fulfilled, but I would expect it to display, simply, the value 10.

Interestingly, if I modify the body of my call to .then() to res => alert(res), the alert displays what I expect, just 10.

Zach M.
  • 74
  • 8
  • 1
    chaining `.then` off a Promise always returns a new Promise. How could it not? Basically, once you have a Promise, there's no way to get a non-Promise from it (other than by doing something directly inside the callback, as with your `alert` example) – Robin Zigmond Jul 19 '22 at 20:47
  • Why wouldn't it?! – jonrsharpe Jul 19 '22 at 20:49
  • @RobinZigmond If I understand correctly, parameter ```res``` in ```.then()``` is the promise returned by the call to ```myAsync()```. If so, I understand why simply returning ```res``` from ```.then()``` displays the promise object. However, at that point, my remaining question is why does ```alert(res)``` produce an alert displaying the result of the promise and not an alert displaying the promise itself? – Zach M. Jul 19 '22 at 20:58
  • @jonrsharpe I mean, please keep in mind that I'm trying to understand. In my mind, the promise has been resolved with a value, so it seemed that ```.then()``` would contain that value. – Zach M. Jul 19 '22 at 21:06
  • 1
    The callback to then _receives_ the value. The method itself returns a promise, and you can chain it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then – jonrsharpe Jul 19 '22 at 21:07
  • 1
    @ZachMcNulty "*parameter `res` in `.then()` is the promise*" - no, it's the result (fulfillment value) of the promise. Notice that a) `.then()` does not return the return value of the callback b) `.then()` always calls the passed callback asynchronously, when the promise fulfills (and [even if the promise already was fulfilled](https://stackoverflow.com/a/28750658/1048572)). It returns a new promise *before* the callback is called. – Bergi Jul 19 '22 at 21:11

0 Answers0