0

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')
    })
  }
  • Does this answer your question? [Throttle amount of promises open at a given time](https://stackoverflow.com/questions/38385419/throttle-amount-of-promises-open-at-a-given-time) – Jeff Bowman Apr 05 '21 at 20:57

2 Answers2

1

I think you can take advantage of async/await.

It may not be exactly what you need but you can fine tune it.

Read about async/await here.

public async getProfits(data) { // add async here
    let responses = [];
    for (let i = 0; i < data.length; i++) {
      let response = await this.getProfit(data[i].symbol);
      console.log(response);
      responses.push(response);
    }
    this.data = this.dataService.ascArray(responses, 'symbol');
  }

AliF50
  • 16,947
  • 1
  • 21
  • 37
1

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');
  });
}
kevlatus
  • 330
  • 1
  • 8
  • It works...Thank you very much. I've looked into your codes and make myself understand and practice each line by line... regards....:) – Ellen Mina Kim Apr 05 '21 at 17:04
  • great to hear, @EllenMinaKim ;) If this has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – kevlatus Apr 05 '21 at 17:41