In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use top-level await to simplify JS. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
JavaScript is a popular programming language, originally designed as a single-threaded and synchronous language, which means that the program needs to run step by step without waiting for external resources or time-consuming computing. If the script requires such resources or calculations, this synchronization behavior will result in an error. This blocks all other processes in the queue from running, whether or not they depend on those blocked tasks.
But long ago, JavaScript introduced a mechanism that allows it to execute the rest of its code while waiting for external resources or time-consuming tasks. This asynchronous behavior is achieved by using callbacks or promise on functions.
What is callback and promise
I will explain these concepts through code. If you already know what a callback promise is, skip to the top-level await section and the sample application.
Callback
In a callback, one function is passed as an argument to another; therefore, the second argument in the following addEventListener function is the callback function. This callback waits for the first click event to occur before executing the second parameter.
Const x = document.getElementsByTagName ('Button'); x [0] .addEventListener (' click', () = > {alert ("I was clicked")})
This waiting behavior makes the code asynchronous. Unlike synchronous code, it can be run step by step without waiting for the resource to download or the time-consuming process to end. Note, however, that not all callback functions are asynchronous.
Promises
Promises is similar to a callback in that it appends a function to the returned object. But there are differences between Promises and callbacks. Promises is specifically designed for asynchronous methods. They have only one argument and a then () function to get the returned results. In addition, it can chain attach multiple .then () and catch () functions.
Fetch ('www.xyz.com/api') .then ((res) = > {let x = res.data; / / do something with received data}) .catch ((err) = > {console.log (err)})
Promises uses event queues and strictly follows the order in which asynchronous tasks are linked.
Async/await
Async/await is a syntax improvement on Promises to avoid chained calls. It makes the code clearer and easier to understand. The await keyword pauses the code until Promises succeeds (resolved) or fails (resolved).
Async function asyncwaitcode () {let getData = await axios ('www.xyzdata.org/api') console.log (getData.data)}
What is the top-level await
All of the above examples make the code in the function block asynchronous, and none of them works at the module level.
However, asynchronous behavior can be implemented at the module level. A module that uses a top-level await initializes its namespace asynchronously before notifying the module's consumer to continue executing its own code.
The following sample code shows how to use the top-level await.
About App
This application will fetch the hottest news data from the News API and present it in the browser. Users can also search news data with relevant search terms. Before we begin, there are a few points to note:
Top-level await is supported in node 13.3 and later
Top-level await is only supported in the ECMAScript module, but Node.js and Express are both CmmonJS modules. CmmonJS does not support the top-level await feature. So I will use import instead of require in my code
Before node 14.x, the top-level await cannot be used directly and needs to be enabled-- harmony
Circular reference modules may cause deadlocks
Build App
1. Create a toplevelawait directory
$mkdir toplevelawait
2. Npm init initialization
$npm init
Add "type": "module" to 3.package.json to support ECMAScript module
"author": "," license ":" ISC "," type ":" module "
4. Create a src directory under the toplevelawait directory. Note that you use mjs as the file suffix.
$touch app.mjs $touch exp.mjs $ls-1 src app.mjs exp.mjs
5. Installation depends on axios, ejs and express
$npm install axios ejs express-save
6. Add the following code to exp.mjs:
Import express from "express" export const exp = await express ()
Notice that we are using await without async. In this way, the express instance will be initialized and then exported to other modules. In this way, you can wait for an instance of the module to be initialized before executing the code that depends on the module.
If a module contains a top-level await, the execution of its parent module stops until the promise is complete. But his brother module will continue to execute, the same as the previous synchronization mode.
Note that module loading in Node.js is also synchronous, meaning that it cannot wait for resources to load asynchronously. But you can wait asynchronously by adding the await keyword before the statement that loads or processes the resource.
Add news APIs
The app uses two free news API to get data. Two API support fallback dependency behavior; if one API fails, the other API will get the data. Both API use API keys:
News API [1]
GNews API [2]
Insert the following code in the app.mjs file. The previous target imports axios and the express instance that is initialized in exp.js. The next section sets up the view engine for display in the browser.
Import {exp} from ". / exp.mjs"; import axios from "axios" exp.set ("view engine", "ejs"); / / dependency fall back let response = ""; let site = true; try {response = await axios ('https://newsapi.org/v2/top-headlines?country=us&apiKey=your-api-key');} catch {response = await axios ("https://gnews.io/api/v3/top-news?token=your-api-key");") Site = false } / / Get top news exp.get ('/', function (req,res) {let responseresponse0 = response.data.articles res.render ('main.ejs', {response0: response0, site:site})) / / searchnews exp.get (' / search', function (req,res) {res.render ("searchnews.ejs")}) exp.get ('/ result', async (req,res) = > {let x = req.query.newtitlesearch Let response1 = {} let data = {} try {let url = 'https://newsapi.org/v2/everything?q='+x+'&apiKey=your-api-key' response1 = await axios (url) } catch {let url = 'https://gnews.io/api/v3/search?q='+x+'&token=your-api-key' response1 = await axios (url)} res.render (' result.ejs', {response1: response1.data.articles, site: site})}) exp.listen (3000)
The most important part is the try catch block, which uses the top-level await to wait for axios to get the data. If, for any reason, axios cannot get data from the first API, the application will use the second API to get the data. Once it gets the data from API, express can render it on the home page.
Try {response = await axios ('https://newsapi.org/v2/top-headlines?country=us&apiKey=your-api-key');} catch {response = await axios ("https://gnews.io/api/v3/top-news?token=your-api-key");})
Next, a route is provided that allows the user to search:
/ / searchnews exp.get ('/ search', function (req,res) {res.render (".. / src/view/searchnews.ejs")})
Finally, another path displays the search results:
Exp.get ('/ result', async (req,res) = > {let x = req.query.newtitlesearch; let response1 = {} let data = {} try {let url = 'https://newsapi.org/v2/everything?q='+x+'&apiKey=your-api-key' response1 = await axios (url)) } catch {let url = 'https://gnews.io/api/v3/search?q='+x+'&token=your-api-key' response1 = await axios (url)} res.render ('. / src/view/result.ejs', {response1: response1.data.articles, site: site})
Write front-end interface
The last part of the application is to write four .ejs HTML files for the front-end page. Save these files in the view folder:
/ / header.ejs newapiapp News app Main Search / / main.ejs
/ / searchnews.ejs Search news / / result.ejs
Run app
Now that APP is complete, you can give it a try.
If you are using node.js v13.3 to v14.0, run:
$node-harmony-top-level-await app.js
If you are using node.js v14.0 or above, you do not need-- harmony flag:
$node app.js
If you have successfully built this app, congratulations on learning a new js feature.
This is the end of this article on "how to use top-level await to simplify JS". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.