0

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)
1
  • async functions wait for each Promise at await to be resolved. Don't use an async function or await, if order does not matter. Commented Feb 17, 2021 at 22:36

2 Answers 2

2

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()

Sign up to request clarification or add additional context in comments.

Comments

0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.