Ad

Forcing A Time Between Requests Using - Async/await Delay

- 1 answer

Have the following function "sendBulkProducts" that receives a array of objects (that are products) and using a API in this case of shopify and send a pair(2) of products for each second until it ends the loop. That is send two products waits one second then sends another two products waits one second and so on.

Using the package delay

But its not waiting the 1 second, so wanted to know what step in code is wrong?

 const sendBulkProducts = (products) => {
        const promisesArray = products.map( async (product,index) => {
            console.log(product);
            console.log('\n\n');
            console.log(index % 2);
            if(index % 2 !== 0){
                insertProductShopify({
                    "product":product
                });
                console.log('wait 1 seconds');
                return await delay(1000);
            }else{
                console.log('send away');
                return insertProductShopify({
                    "product":product
                });
            }
        });
        return Promise.all(promisesArray);
    }

const insertProductShopify = async product => {
  await request({
   .....
  });
}
Ad

Answer

products.map send all products in parallel, you need to iterate through them instead.

const sendBulkProducts = async(products) => {
  let index = 0
  for (let product of products) {
    insertProductShopify({product})
    if (++index % 2 == 0){
      await delay(1000)
    }
  }
}
Ad
source: stackoverflow.com
Ad