user1971598
user1971598

Reputation:

Have result of entire recursion be a Promise

I have this code:

export const photos_pipeline = (
  images_at_time,
  only_those_missing,
  resize_photos,
  remote_analysis,
  persist_to_realm
) => {
  const pull = (after = null) => {
    const query =
      after !== null
        ? {first: images_at_time, assetType: 'Photos', after}
        : {first: images_at_time, assetType: 'Photos'};

    CameraRoll.getPhotos(query).then(({edges, page_info}) =>
      only_those_missing(edges)
        .then(resize_photos)
        .then(remote_analysis)
        .then(persist_to_realm)
        .then(() => {
          if (page_info.has_next_page === true) pull(page_info.end_cursor);
          else return;
        })
    );
  };

  return Promise.resolve(pull());
};

Which I want to have be finished as a Promise, that is, I want effectively a join on all the recursion but I am not clear what the right way to go about this is.

I know that the trailing Promise.resolve is an already resolved Promise that perhaps it ought to be a new Promise but that doesn't clear up the issue of joining on all the recursion. Trying right now to have an accumulator array and then a Promise.all on the result, but posting here in the meantime.

Thanks.

EDIT: No bluebird or anything but native Promise.

Upvotes: 0

Views: 64

Answers (2)

Chris Johnson
Chris Johnson

Reputation: 21

You need to first return the result of CameraRoll.getPhotos(...) so that pull returns a promise (this will eliminate the need for return Promise.resolve(pull()); and you can just make it return pull();

You also need to make sure that when you recurse on pull, you again return it inside the handler, so that the promise returned by CameraRoll.getPhotos() will wait for the recursion to resolve before resolving itself.

Thus something like this:

const pull = () => {
    return CameraRoll.getPhotos().then(...
        return pull(...);
     });
};

return pull();

Upvotes: 1

SLaks
SLaks

Reputation: 887305

You need to make your pull() function return its promise chain.

You can then just call that function and return its promise; you don't need to do anything else.

You also need to return it when calling it recursively, or your then() callback won't actually wait for it.

Upvotes: 3

Related Questions