Have you ever needed to return a Promise that you can then resolve from a completely different part of your code?

A lot of solutions online seem to suggest moving large amounts of code into your promise which is not ideal. Or you’re told you are “doing it wrong” and should be using await to avoid returning control back to the caller until the async process is complete, and whilst I agree with that generally, it’s just not always possible.

So, the solution is a simple one. Store a reference to the promises resolve & reject functions that you can call from somewhere else.

See it working here: https://jsfiddle.net/5dq6rohj/

Need a more concrete use case?

Recently I needed to open a WebSocket connection, wait for a custom message to be sent back to me via the WebSocket libraries message callback, and then my application could continue doing its thing. Here’s an overly simplified and redacted version of that code.

 

I hope someone finds this technique useful. It is certainly not always the best approach, but if you can’t simply await your async code then this is a viable solution.