[Fixed] Promise request after finishing one by one

Issue

I’ve used Promise.all() to get every request.

But I have got an error message from the server that I requested too many calls in a short period because the number of array I requested is over 100.

How can I improve my Promise codes to calling a next request after finishing the first request?

 public getProfits(data) {
    return Promise.all(
      data.map((obj) => {
        return this.getProfit(obj.symbol).then(rawData => {
          obj.stat = rawData
          return obj;
        });
      })
    ).then(data => {
      this.data = this.dataService.ascArray(data, 'symbol')
    })
  }

Solution

If your environment allows for using async/await, the simplest solution might be this:

public async getProfits(data) {
  for(const obj of data) {
    obj.stat = await this.getProfit(obj.symbol);
  }
  this.data = this.dataService.ascArray(data, 'symbol');
}

Otherwise you might need to do this:

public getProfits(data) {
  let p = Promise.resolve();

  for(const obj of data) {
    p = p.then(() => {
       return this.getProfit(obj.symbol).then(rawData => obj.stat = rawData);
    });
  }
  p.then(() => {
    this.data = this.dataService.ascArray(data, 'symbol');
  });
}

Leave a Reply

(*) Required, Your email will not be published