Home >Web Front-end >Front-end Q&A >How to use await in nodejs
In nodejs, await is used to pause execution in a non-blocking manner, waiting for a promise's asynchronous request, and waiting for the asynchronous method to complete execution; await can be used in async functions to wait for the return of an async function Value; promise returns an unsuccessful rejection, and the rejection value will be thrown and can be captured by "try/catch".
The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.
Async/await usage was introduced in Node.js 7 night, but it is only possible to officially activate the async/await function in Node.js 8 and Javascript V8.
What is async/await? How to implement asynchronous operations using Promise in the past. The following case shows how to use Promise and Fetch API to capture data:
function getTrace () { return fetch('https://www.jdon.com', { method: 'get' }) } getTrace() .then() .catch()
Using async/await, you can pause execution in a non-blocking manner and wait for the result to return. If the promise returns an unsuccessful rejection, the rejection value will be thrown and can be captured by try/catch. The above case can be written as follows using async/await:
function async getTrace () { let pageContent try { pageContent = await fetch('https://www.jdon.com', { method: 'get' }) } catch (ex) { console.error(ex) } return pageContent } getTrace() .then()
Let’s look at the case of using async/await in Node.js, using setimeout to delay the execution of a function, and using async/await encapsulation:
// app.js const timeout = function (delay) { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, delay) }) } async function timer () { console.log('timer started') await Promise.resolve(timeout(100)); console.log('timer finished') } timer()
Create this app.js file and run:
node app.js
If it cannot run, it may be that nodejs is a nightly version and does not officially support async/await. The command line should be:
node --harmony-async-await app.js
Recommended learning: "nodejs video tutorial"
The above is the detailed content of How to use await in nodejs. For more information, please follow other related articles on the PHP Chinese website!