SoFunction
Updated on 2025-04-10

20 practical skills for JS async/await you have to know

20 Js async/await usages that you have to know

1. Basic usage

asyncThe function returns aPromise,andawaitKeywords can be pausedasyncFunction execution, waitingPromisesolve.

async function fetchData() {
    let data = await fetch('url');
    data = await ();
    return data;
}

2. Error handling

usetry...catchStructural processingasync/awaitError in.

async function fetchData() {
    try {
        let response = await fetch('url');
        response = await ();
        return response;
    } catch (error) {
        ('Fetching data error:', error);
    }
}

3. Parallel execution

()Can be used to execute multipleawaitoperate.

async function fetchMultipleUrls(urls) {
    const promises = (url => fetch(url).then(r => ()));
    return await (promises);
}

4. Conditional asynchronous

Perform according to the conditionsawait

async function fetchData(condition) {
    if (condition) {
        return await fetch('url');
    }
    return 'No fetch needed';
}

5. Await in a loop

Use in a loopawaitWhen, each iteration will wait.

async function sequentialStart(urls) {
    for (const url of urls) {
        const response = await fetch(url);
        (await ());
    }
}

6. Asynchronous iterator

For asynchronous iterators (for example Streams), you can usefor-await-ofcycle.

async function processStream(stream) {
    for await (const chunk of stream) {
        (chunk);
    }
}

7. Deconstruct immediately after await

Directly inawaitDeconstruction is used after expression.

async function getUser() {
    const { data: user } = await fetch('user-url').then(r => ());
    return user;
}

8. Use default parameters to avoid invalid await

ifawaitIt may be unnecessary, and you can use the default parameters to avoid waiting.

async function fetchData(url = 'default-url') {
    const response = await fetch(url);
    return ();
}

9. await in class method

Use in class methodsasync/await

class DataFetcher {
    async getData() {
        const data = await fetch('url').then(r => ());
        return data;
    }
}

10. The async arrow function that is executed immediately

Can be executed immediatelyasyncArrow function.

(async () => {
    const data = await fetch('url').then(r => ());
    (data);
})();

11. Use async/await for delay

useasync/awaitImplement delay.

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedLog(item) {
    await delay(1000);
    (item);
}

12. Use async/await to handle event listeners

Use in event handler functionsasync/await

('button').addEventListener('click', async (event) => {
    ();
    const data = await fetch('url').then(r => ());
    (data);
});

13. Processing arrays in sequential manner

useasync/awaitProcess the array in a definite order.

async function processArray(array) {
    for (const item of array) {
        await delayedLog(item);
    }
    ('Done!');
}

14. Combining async/await with destructuring and spread operators

Use in combinationasync/await, deconstruct and expand operators.

async function getConfig() {
    const { data, ...rest } = await fetch('config-url').then(r => ());
    return { config: data, ...rest };
}

15. Use async/await in object methods

WillasyncMethods are attributes of objects.

const dataRetriever = {
    async fetchData() {
        return await fetch('url').then(r => ());
    }
};

16. Asynchronous generator function

useasyncGenerator function combinationyield

async function* asyncGenerator(array) {
    for (const item of array) {
        yield await processItem(item);
    }
}

17. Use top await

Used on top of the moduleawait(Requires specific JavaScript environment support).

// ECMAScript 2020 introduces top await features, pay attention to compatibility when deployingconst config = await fetch('config-url').then(r => ());

18. Async/await combined with IIFE

WillasyncFunctions are combined with Immediate Execution Function Expression (IIFE).

(async function() {
    const data = await fetch('url').then(r => ());
    (data);
})();

19. Optimize recursive calls using async/await

Optimize recursive functions.

async function asyncRecursiveFunction(items) {
    if ( === 0) return 'done';
    const currentItem = ();
    await delay(1000);
    (currentItem);
    return asyncRecursiveFunction(items);
}

20. Use await in switch statement

existswitchEach statementcaseUsed inawait

async function fetchDataBasedOnType(type) {
    switch (type) {
        case 'user':
            return await fetch('user-url').then(r => ());
        case 'post':
            return await fetch('post-url').then(r => ());
        default:
            throw new Error('Unknown type');
    }
}

The above are the detailed contents of 20 practical JS async/await techniques that you have to know. For more information about JS async/await techniques, please follow my other related articles!