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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
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…
Sadly, the answer is: No.
See the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
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 insideasync function
.At least you have to do:
in your main code.
Or, using an IIFE - thanks to Robert Klep for the suggestion:
Or, if you like punctuation:
Other options
There are some other options to handle concurrency in Node, like:
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.