Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I synchronously determine a JavaScript Promise's state?

I have a pure JavaScript Promise (built-in implementation or poly-fill):

var promise = new Promise(function (resolve, reject) { /* ... */ });

From the specification, a Promise can be one of:

  • 'settled' and 'resolved'
  • 'settled' and 'rejected'
  • 'pending'

I have a use case where I wish to interrogate the Promise synchronously and determine:

  • is the Promise settled?

  • if so, is the Promise resolved?

I know that I can use #then() to schedule work to be performed asynchronously after the Promise changes state. I am NOT asking how to do this.

This question is specifically about synchronous interrogation of a Promise's state. How can I achieve this?

like image 901
jokeyrhyme Avatar asked Oct 10 '22 18:10

jokeyrhyme


People also ask

How do I know if JavaScript promise is fulfilled?

The best place to know if a promise is resolved is in . then(). Testing if a Promise is fullfilled would create a polling loop which is most likely the wrong direction. async/await is a nice construct if you'd like to reason async code synchronously.

What are the 3 states of a JavaScript promise?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

Are JavaScript promises synchronous?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.


1 Answers

No such synchronous inspection API exists for native JavaScript promises. It is impossible to do this with native promises. The specification does not specify such a method.

Userland libraries can do this, and if you're targeting a specific engine (like v8) and have access to platform code (that is, you can write code in core) then you can use specific tools (like private symbols) to achieve this. That's super specific though and not in userland.

like image 113
Benjamin Gruenbaum Avatar answered Oct 16 '22 18:10

Benjamin Gruenbaum