You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/11-async/08-async-await/article.md
+11-6
Original file line number
Diff line number
Diff line change
@@ -121,16 +121,22 @@ showAvatar();
121
121
122
122
Pretty clean and easy to read, right? Much better than before.
123
123
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>.
126
126
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
129
131
let response = await fetch('/article/promise-chaining/user.json');
130
132
let user = await response.json();
133
+
134
+
console.log(user);
131
135
```
132
136
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:
134
140
135
141
```js
136
142
(async () => {
@@ -140,7 +146,6 @@ But we can wrap it into an anonymous async function, like this:
140
146
})();
141
147
```
142
148
143
-
P.S. New feature: starting from V8 engine version 8.9+, top-level await works in [modules](info:modules).
0 commit comments