JavaScript的async与await应用

在Chrome的Console下处理1000个请求,耗时50s内所有完成

const fetch = require('node-fetch')

async function fetchAndDecode(url, i) {
    let response = await fetch(url, {
        "headers": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp," +
                "image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Host": "httpbin.org",
            "Pragma": "no-cache",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (" +
                "KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
        },
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": null,
        "method": "GET",
        "mode": "cors",
        "credentials": "omit"
    });

    let content = await response.text();
    console.log("=" + i)
    return content;
}


async function displayContent() {
    const start_time = new Date();
    let tasks = []
    for (let i = 0; i < 1000; i++) {
        tasks.push(fetchAndDecode('http://httpbin.org/get', i))
    }
    let values = await Promise.all(tasks);
    for (const value of values) {
        console.log(value)
    }
    const end_time = new Date();
    const diff_time = end_time.getTime() - start_time.getTime()
    console.log("diff_time: " + diff_time / 1000)
}

displayContent()
    .catch((e) =>
        console.log(e)
    );
复制代码