0

I have that function which gets data from API (getFollowedArtistsAdapter) until it's not the last page of results. I want to make it all as one Promise. But when I look at this function it seems to be illegible and unnecessarily convoluted.

const getArtists = () => {
  let afterGet = null;
  let items = [];

  return new Promise(function promiseCallback(resolve, reject) {
    const afterParam = afterGet ? {limit: 50, after: afterGet} : {limit: 50};

    getFollowedArtistsAdapter(afterParam)
      .then((data) => {
        items = items.concat(data.artists.items);

        if(data.artists.next){
          afterGet = data.artists.items[data.artists.items.length - 1].id;
          promiseCallback(resolve, reject);
        } else {
          return updateStoreArtists(items).then(() => resolve());
        }
      });
  });
}

Any ideas how to split it?

Laudinio
  • 33
  • 5
  • i don't think this code is convoluted *in terms of how it's laid out* but it might be a problem that you are updating outside variables in a promise. – VLAZ Oct 02 '19 at 07:52
  • Possibly relevant: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Oct 02 '19 at 07:59

1 Answers1

2

Consider just calling getFollowedArtistsAdapter, which returns a recursive call of itself (or updateStoreArtists) at the end, if needed, without creating an unnecessary new Promise:

const getArtists = () => {
  let items = [];
  return getFollowedArtistsAdapter({ limit: 50 })
    .then((data) => {
      const thisItems = data.artists.items;
      items = items.concat(thisItems);
      if (data.artists.next){
        const after = thisItems[thisItems.length - 1].id;
        return getFollowedArtistsAdapter({limit: 50, after });
      }
    })
    .then(() => {
      return updateStoreArtists(items);
    });
}

This way, all getFollowedArtistsAdapter calls will be completed in the first .then. When the first .then resolves, items will be fully populated, and the second .then will return the Promise from updateStoreArtists.

Avoid the explicit promise construction antipattern.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320