欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

20個(gè)你不得不知道的JS async/await實(shí)用技巧

 更新時(shí)間:2023年12月13日 09:56:59   作者:慕仲卿  
JavaScript的async和await關(guān)鍵詞是現(xiàn)代JavaScript異步編程的核心,它們讓異步代碼看起來(lái)和同步代碼幾乎一樣,使得異步編程變得更加直觀和易于管理,本文介紹20個(gè)關(guān)于async/await的實(shí)用技巧,將大大提升編程效率和代碼的清晰度,需要的朋友可以參考下

20個(gè)你不得不知道的Js async/await用法

1. 基礎(chǔ)用法

async函數(shù)返回一個(gè)Promise,而await關(guān)鍵詞可以暫停async函數(shù)的執(zhí)行,等待Promise解決。

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

2. 錯(cuò)誤處理

使用try...catch結(jié)構(gòu)處理async/await中的錯(cuò)誤。

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

3. 并行執(zhí)行

Promise.all()可以用來(lái)并行執(zhí)行多個(gè)await操作。

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

4. 條件異步

根據(jù)條件執(zhí)行await

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

5. 循環(huán)中的await

在循環(huán)中使用await時(shí),每次迭代都會(huì)等待。

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

6. 異步迭代器

對(duì)于異步迭代器(例如Node.js中的Streams),可以使用for-await-of循環(huán)。

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

7. await之后立即解構(gòu)

直接在await表達(dá)式后使用解構(gòu)。

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

8. 使用默認(rèn)參數(shù)避免無(wú)效的await

如果await可能是不必要的,可以使用默認(rèn)參數(shù)避免等待。

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

9. await在類的方法中

在類的方法中使用async/await。

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

10. 立刻執(zhí)行的async箭頭函數(shù)

可以立即執(zhí)行的async箭頭函數(shù)。

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

11. 使用async/await進(jìn)行延時(shí)

利用async/await實(shí)現(xiàn)延時(shí)。

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

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

12. 使用async/await處理事件監(jiān)聽器

在事件處理函數(shù)中使用async/await

document.getElementById('button').addEventListener('click', async (event) => {
    event.preventDefault();
    const data = await fetch('url').then(r => r.json());
    console.log(data);
});

13. 以順序方式處理數(shù)組

使用async/await以確定的順序處理數(shù)組。

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

14. 組合async/await與destructuring以及spread運(yùn)算符

結(jié)合使用async/await,解構(gòu)和展開操作符。

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

15. 在對(duì)象方法中使用async/await

async方法作為對(duì)象的屬性。

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

16. 異步生成器函數(shù)

使用async生成器函數(shù)結(jié)合yield

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

17. 使用頂級(jí)await

在模塊頂層使用await(需要特定的JavaScript環(huán)境支持)。

// ECMAScript 2020引入頂級(jí)await特性, 部署時(shí)注意兼容性
const config = await fetch('config-url').then(r => r.json());

18. async/await與IIFE結(jié)合

async函數(shù)與立即執(zhí)行函數(shù)表達(dá)式(IIFE)結(jié)合。

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

19. 使用async/await優(yōu)化遞歸調(diào)用

優(yōu)化遞歸函數(shù)。

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

20. 在switch語(yǔ)句中使用await

switch語(yǔ)句的每個(gè)case中使用await

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

以上就是20個(gè)你不得不知道的JS async/await實(shí)用技巧的詳細(xì)內(nèi)容,更多關(guān)于JS async/await技巧的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論