In JavaScript, await
keywords are part of the asynchronous functions feature introduced in ES2017 (also known as ES8), which allows us to write asynchronous code in a more intuitive and synchronous way. When using it await
, we must place it async
inside the function. This article will use 10 pieces of code to gain an in-depth understanding of await
how it works and is used in JavaScript.
Code snippet 1: await
Resolving with Promise
async function fetchValue() {
return new Promise(resolve => setTimeout(() => resolve(42), 1000));
}
async function demo() {
const value = await fetchValue();
console.log(value); //
}
demo();
This code shows await
the basic usage of waiting for a Promise to resolve and returning the result.
Code snippet 2: Error handling await
intry...catch
async function failingOperation() {
return Promise.reject(new Error('Operation failed'));
}
async function demo() {
try {
await failingOperation();
} catch (error) {
console.error(error.message); // "Operation failed"
}
}
demo();
Here is a demonstration of how to use try...catch
capture await
expressions to potentially throw errors.
Code snippet 3: Concurrent execution of await
ANDPromise.all
async function demo() {
const promise1 = fetchValue(); //
const promise2 = fetchValue();
const [result1, result2] = await Promise.all([promise1, promise2]);
console.log(result1, result2); //
}
demo();
This code shows how to Promise.all
wait for multiple Promises to resolve concurrently.
Code snippet 4: await
Use in loops
async function demo() {
for (let i = 0; i < 5; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(i); //
}
}
demo();
This code demonstrates how to use a loop await
to perform asynchronous operations sequentially.
Code snippet 5: await
Promise with immediate resolution
async function demo() {
const value = await Promise.resolve(42);
console.log(value); //
}
demo();
Even if the Promise has resolved, await
it will still wait and return the resolved value.
Code snippet 6: await
Return value with asynchronous function
async function asyncFunc() {
return 42;
}
async function demo() {
const value = await asyncFunc();
console.log(value); //
}
demo();
The value returned by the asynchronous function will be implicitly wrapped into a Promise and await
will wait for the Promise to be resolved.
Code snippet 7: await
Chained calls with Promise
async function demo() {
const value = await fetchValue().then(v => v * 2);
console.log(value); //
}
demo();
Even if it is used await
, it can still be combined with Promise’s chained calls to handle asynchronous results.
Code snippet 8: await
and asynchronous iteration
async function* asyncGenerator() {
yield 1;
yield await fetchValue(); //
yield 3;
}
async function demo() {
for await (const value of asyncGenerator()) {
console.log(value); //
}
}
demo();
This code demonstrates await
use with asynchronous iterators.
Code snippet 9: await
Use in classes
class MyClass {
async fetchData() {
return await fetchValue(); //
}
}
async function demo() {
const instance = new MyClass();
const data = await instance.fetchData();
console.log(data); //
}
demo();
It can also be used in class methods await
to handle asynchronous operations.
Code snippet 10: await
and asynchronous I/O operations
const fsPromises = require('fs').promises;
async function demo() {
const content = await fsPromises.readFile('./example.txt', 'utf8');
console.log(content); //
}
demo();
This code demonstrates await
use in conjunction with asynchronous I/O operations in Node.js. Through this await
, we can write asynchronous file reading code in a synchronous manner, making the code more intuitive and understandable.
Although the above code is relatively basic and simple. But it has fully reflected all aspects of the use of the await keyword in JavaScript. If you are still timid when facing await, it is better to save this article and type it over frequently to consolidate your practice. Through this method, I believe that I will be able to have a deeper understanding of it in a short time, thereby laying a solid foundation for JavaScript asynchronous programming.