How to use await in nodejs

WBOY
Release: 2022-06-29 15:54:12
Original
4092 people have browsed it

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".

How to use await in nodejs

The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.

How to use await in nodejs

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()
Copy after login

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template