Search code examples
javascriptecmascript-6promisees6-promise

Get value of resolved Promise in sync


If we know that a Promise is definitely resolved, how can we access the value and if we can't, why not?

let a = Promise.resolve(123);

console.log(a.value); // ???

The following does not work- it prints "First, Last, 123"

console.log("First");
Promise.resolve(123).then(console.log);
console.log("Last");

I'm asking how to get the value of an already resolved Promise synchronously and if that's not possible, why not?


Solution

  • No, it is not possible to do this. This is by design.

    The Promise A+ specification is meant to be used as a simple, consistent way to deal with asynchronous operations. One of the constraints is that passing a new callback on to then() on an already resolved promise will always execute on a later tick in the event loop, so things are consistent.

    Adding a secondary way to inspect promise results would not have been impossible. It would probably have been quite easy to do so, but there's at least 2 problems with adding this to the specification:

    1. If you're looking to build a specification, you want it to be as simple as possible. The specification itself actually only defines the then() function.
    2. By adding this feature, you're opening the door to hordes of developers getting even more confused about something that's already hard to grok.

    Promises and asynchronous operations are hard for people to understand. I see questions here daily about promises and not 'getting' it. If non-async way to access promise results would be added to the default promise, I'd imagine that this would be an even larger amount. It's good to try and enforce 'the right way' of doing things.

    However, this decision is not simply made for you. You're not stuck there. You can very easily build your own version of a promise that has this feature, and still works with existing promises. As long as your object has a then() function that behaves according to Promises/A+ you can do with the rest of the object whatever you want.