Is It Possible To Use Await Without Async In Js
Solution 1:
No. The await
operator only makes sense in an async
function.
edit — to elaborate: the whole async
and await
deal can be thought of as being like a LISP macro. What that syntax does is inform the language interpretation system of what's going on, so that it can in effect synthesize a transformation of the surrounding code into a Promise-based sequence of callback requests.
Thus using the syntax is an implicit short-cut to coding up the explicit Promise stuff, with calls to .then()
etc. The runtime has to know that a function is async
because then it knows that await
expressions inside the function need to be transformed to return Promises via a generator mechanism. And, for overlapping reasons, the async
decoration on the function declaration tells the language that this is really a function that returns a Promise and that it needs to deal with that.
So, it's complicated. The process of improving and extending JavaScript has to account for the fact that there's an unimaginably massive amount of JavaScript code out in the world, and so in almost all cases no new feature can cause a page untouched since 2002 to fail.
edit — Now, here in 2021, there are rules for how an await
call works in the outer level of a module. It's not quite the same as how it works in an async
function situation, but it's similar.
Solution 2:
It's proposed to ECMAScript.
Chrome/Chromium (and anything with an up-to-date V8-based JS engine) has a working implementation that appears to be compliant with the specification.
The proposal itself is at stage 3.
More info:
Solution 3:
Top-level await (await without async) is not yet a JavaScript feature.
However, as of version 3.8, it can be used in Typescript.
In order to use it, the following configuration is required (in tsconfig.json
):
"module":"esnext"// or "system""target":"es2017"// or higher
More information:
https://typescript.tv/new-features/top-level-await-in-typescript-3-8/
Post a Comment for "Is It Possible To Use Await Without Async In Js"