bdui
bdui

Reputation: 13

How to send multiple requests asynchronously in JavaScript?

I need to send 3 requests at once. I got some async function which works, but sends requests one by one. Where is the problem ?

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)

Upvotes: 0

Views: 6169

Answers (2)

rjmunro
rjmunro

Reputation: 28076

If you remove the await before the send("POST", ..., it won't wait for each send to finish before starting the next one. All the send's will just happen in the background. As you don't seem to be checking the result of the send, this should work fine in your case.

If you want to run all the sends in parallel, but wait until they have all finished, you can change your for loop to a map, return the send values and await all of them at once, something like:

    if(cart_json.items.length === 0){
        await Promise.all([296752801, 299028489, 474510260].map((item) => {
            let json = JSON.stringify({"version": 1, "qty": 1, "gift_card_custom_price": 0, "id": item})
            return send("POST", "https://www.mediaexpert.pl/cart/pre-x-add?precart=true", json)
        }));
        return true
    }

Upvotes: 0

GDias
GDias

Reputation: 115

You're using async/await in your function. So node is going to wait for each request. If you're in need to wait for all the functions to execute and finish, take a look at Promise.all()

Upvotes: 2

Related Questions