ezdin gharbi
ezdin gharbi

Reputation: 19

Adding delay to promises

so I have a loop for creating promise when I do a request to a certain Url:

for (let j = 1; j < nbRequest; j++)

{
 const currentPromise = new Promise((resolve, reject) => {
    request(
      `someUrl${j}`,
      (error, response, body) => {
        if(error || !response) {
          console.log("Error: " + error);
        }

    console.log("Status code: " + response.statusCode + ", Connected to the page");

    var $ = cheerio.load(body);
    let output = {
      ranks: [],
      names: [],
      numbers: [],
    };

   //some stuff to do

    console.log("HERE 1");
    return resolve(output);
  }
);
  });
  promises.push(currentPromise);
}

After that I'm writing result of my promises in a csv file :

Promise.all(promises).then((outputs) => {
  console.log('Request received');
  let ranks;
  let names;
  let numbers;

  outputs.forEach((output) => {
    ranks = _.concat(ranks, output.ranks);
    names = _.concat(names, output.names);
    numbers = _.concat(numbers, output.numbers);
  });

  for (i = 0; i < ranks.length; i++)
  {
    writer.write({Rang: ranks[i], Nom: names[i] , Nombre: numbers[i]});
  }
});

But here's the problem: I'm willing to add a delay between each promise. Any idea ?

Upvotes: 0

Views: 622

Answers (2)

macdja38
macdja38

Reputation: 613

You could potentially use the loop index to schedule each of the tasks inside the promises for a future time. For example your top section of code would look like this.

for (let j = 1; j < nbRequest; j++) {
  const currentPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      request(
        `someUrl${j}`,
        (error, response, body) => {
          if (error || !response) {
            console.log("Error: " + error);
          }
          console.log("Status code: " + response.statusCode + ", Connected to the page");

          var $ = cheerio.load(body);
          let output = {
            ranks: [],
            names: [],
            numbers: [],
          };

          //some stuff to do

          console.log("HERE 1");
          return resolve(output);
        })
    }, 1000 * j);
  });
  promises.push(currentPromise);
}

Upvotes: 0

rsp
rsp

Reputation: 111316

If you want delays between those functions then you shouldn't use Promise.all in the first place.

When you use async and await plus Bluebird for some nice addons, then you'll be able to use elegant things like this:

const { delay } = require('bluebird');

and in an async function:

doSomething();
await delay(100);
doSomethingElse();
await delay(3000);

// ...

Any time where you need complex time-dependent logic you should really use async/await if you don't want your code to get too complex.

For more info, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

Upvotes: 1

Related Questions