Using top-level await in Node.js and a browser environment
--发布于 2023-04-20 09:59:56
If you're trying to use the await
keyword on the top level of your Node.js application, make sure to set the type
attribute to module
in your package.json
file.
If you don't have a package.json
file, create one by using the npm init -y
command (only if you don't have one already).
npm init -y
Open the package.json
file at the root directory of your project and set the type
attribute to module
.
{
"type": "module",
// ... your other settings
}
Now you can use top-level await
in your Node.js code.
const result = await Promise.resolve(42);
console.log(result); // 👉️ 42
If you're on the browser, set the type
attribute to module
on your script tag.
<script type="module" src="index.js"></script>
Now you can use the top-level await
syntax on the browser.
const result = await Promise.resolve(42);
console.log(result); // 👉️ 42
--更新于 2023-04-20 10:01:06