How to access the result of a Promise synchronously?

Let me start with the fact that I like asynchronous code. I would never wrap async code in a sync wrapper in production, but it is still something that I want to learn how to do. I am talking about specifically in Node.JS, not the browser. There are many ways to access the result of an async function synchronously like using child_process.spawnSync or a worker and Atomics. The issue with these ways is this:

let prom = Promise.resolve(4);
// It is now impossible (as far as I know) to access the result of prom synchronously

Promises cannot be sent in a postMessage call, so a worker cannot access them and wait for them to finish synchronously or at all. One might think, why not do this:

let prom = Promise.resolve(4);
prom.then(res => global.result = res);
while (!global.result) {}; // Do nothing
// Once the loop finishes, the result *would* be available
console.log(global.result); // => 4

Of course, this doesn’t work. The event loop waits executes the while loop completely before even beginning to deal with the callback function of prom.then. This causes an infinite loop. So this makes me ask, "Is there a synchronous task that has to execute not ordinarily to allow for the waiting of a promise?"

Edit
By the way, I totally understand async/await. If I am using a Node.JS module, then I can just do:

let resolved = await prom;

Or if I am not, I can wrap the whole script in an async function and do the same thing. However, the goal is to be able to get the access of a result avoiding await OR using await in an asynchronous context that is able to be accessed and waited for from a synchronous context.

Source: Ask Javascript Questions

LEAVE A COMMENT