In JavaScript, awaitkeywords 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 asyncinside the function. This article will use 10 pieces of code to gain an in-depth understanding of awaithow it works and is used in JavaScript.

Code snippet 1: awaitResolving 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 awaitthe basic usage of waiting for a Promise to resolve and returning the result.

Code snippet 2: Error handling awaitintry...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...catchcapture awaitexpressions to potentially throw errors.

Code snippet 3: Concurrent execution of awaitANDPromise.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.allwait for multiple Promises to resolve concurrently.

Code snippet 4: awaitUse 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 awaitto perform asynchronous operations sequentially.

Code snippet 5: awaitPromise with immediate resolution

async function demo() {
    const value = await Promise.resolve(42);
    console.log(value); // 
}
demo();

Even if the Promise has resolved, awaitit will still wait and return the resolved value.

Code snippet 6: awaitReturn 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 awaitwill wait for the Promise to be resolved.

Code snippet 7: awaitChained 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: awaitand 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 awaituse with asynchronous iterators.

Code snippet 9: awaitUse 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 awaitto handle asynchronous operations.

Code snippet 10: awaitand 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 awaituse 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.

Leave a Reply

Your email address will not be published. Required fields are marked *