Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use await outside async

Is there a way to make the javascript await keyword work outside async functions? I would like to be able to freeze the entire call-stack (instead of just the rest of the async function), to be resumed once the particular promise returns a value. Sadly a powerful await like that is currently gimped or not implemented yet. I tried to make nodent.js work, but due to my custom loader and dynamic functions it's unfortunately impractical.

like image 672
John Smith Avatar asked Mar 15 '26 22:03

John Smith


2 Answers

Is there a way to make the javascript await keyword work outside async functions?

Sadly, the answer is: No.

See the docs:

The await expression causes async function execution to pause, to wait for the Promise's resolution, and to resume the async function execution when the value is resolved. [emphasis added]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

I would like to be able to freeze the entire call-stack (instead of just the rest of the async function), to be resumed once the particular promise returns a value.

But how could your promise return a value if the entire call-stack was frozen? It would be stuck forever.

More details

To use await you need to be inside async function.

At least you have to do:

async function main() {
  // use await here
}
main();

in your main code.

Or, using an IIFE - thanks to Robert Klep for the suggestion:

void async function main() {
    // use await here
}();

Or, if you like punctuation:

(async () => {
    // use await here
})();

Other options

There are some other options to handle concurrency in Node, like:

  • https://www.npmjs.com/package/co
  • https://www.npmjs.com/package/bluebird-co
  • https://www.npmjs.com/package/async-co
  • http://bluebirdjs.com/docs/api/promise.coroutine.html
  • http://taskjs.org/

none of which will freeze the call stack, however, as it would have the same effect as running kill -STOP with your own process ID and waiting for the stopped process to resume itself.

like image 97
rsp Avatar answered Mar 17 '26 11:03

rsp


Given you are looking for a hack, not a proper promise-based concurrency solution, have a look at node-fibers (there are similar ones, but afaik this is the most popular, with multiple abstractions built around it). It does allow you to halt the current fiber in any synchronous function until something asynchronous happens that runs in a different fiber. Which of course is a horrible idea, but well…

like image 27
Bergi Avatar answered Mar 17 '26 11:03

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!