首页 > 解决方案 > 如何在 JavaScript 中异步发送多个请求?

问题描述

我需要一次发送 3 个请求。我得到了一些可以工作的异步功能,但会一一发送请求。哪里有问题 ?

async function fetcher(){
    const cart = await send("GET", "https://www.mediaexpert.pl/cart/mini/data")
    const cart_json = JSON.parse(cart)
    if(cart_json.items.length === 0){
        for(let item of [296752801, 299028489, 474510260]){
            let json = JSON.stringify({"version": 1, "qty": 1, "gift_card_custom_price": 0, "id": item})
            await send("POST", "https://www.mediaexpert.pl/cart/pre-x-add?precart=true", json)
        }
        return true
    }
    return false
}

const interval = setInterval(()=>{
    fetcher().then(resp=>{
        if(resp === false){clearInterval(interval)}
    })
}, 500)

标签: javascript

解决方案


您在函数中使用 async/await。所以节点将等待每个请求。如果您需要等待所有函数执行并完成,请查看Promise.all()


推荐阅读