Skip to content

Commit 97fd3dd

Browse files
committed
Merge branch 'master' of github.com:javascript-tutorial/en.javascript.info into sync-3699f73b
2 parents 9d1f390 + 3699f73 commit 97fd3dd

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

1-js/11-async/08-async-await/article.md

+11-6
Original file line numberDiff line numberDiff line change
@@ -121,16 +121,22 @@ showAvatar();
121121
122122
Pretty clean and easy to read, right? Much better than before.
123123
124-
````smart header="`await` won't work in the top-level code"
125-
People who are just starting to use `await` tend to forget the fact that we can't use `await` in top-level code. For example, this will not work:
124+
````smart header="Modern browsers allow top-level `await` in modules"
125+
In modern browsers, `await` on top level works just fine, when we're inside a module. We'll cover modules in article <info:modules-intro>.
126126
127-
```js run
128-
// syntax error in top-level code
127+
For instance:
128+
129+
```js run module
130+
// we assume this code runs at top level, inside a module
129131
let response = await fetch('/article/promise-chaining/user.json');
130132
let user = await response.json();
133+
134+
console.log(user);
131135
```
132136
133-
But we can wrap it into an anonymous async function, like this:
137+
If we're not using modules, or [older browsers](https://caniuse.com/mdn-javascript_operators_await_top_level) must be supported, there's a universal recipe: wrapping into an anonymous async function.
138+
139+
Lke this:
134140
135141
```js
136142
(async () => {
@@ -140,7 +146,6 @@ But we can wrap it into an anonymous async function, like this:
140146
})();
141147
```
142148
143-
P.S. New feature: starting from V8 engine version 8.9+, top-level await works in [modules](info:modules).
144149
````
145150

146151
````smart header="`await` accepts \"thenables\""

0 commit comments

Comments
 (0)