简体   繁体   中英

forcing a time between requests using - async/await delay

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({
   .....
  });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM