hiroshi
hiroshi

Reputation: 7251

Proper way to recurse Q.Promise

I do something like this. It seems to work for me, but is it OK? Is there any better way?

function myPromise(options) {
  return Q.Promise(function(resolve, reject, notify) {
    doSomthingAsync(options, function(resp) {
       notify(resp);
      if (resp.nextPageToken) {
        options.pageToken = resp.nextPageToken;
        myPromise(options).then(resolve, reject, notify);
      } else {
        resolve(resp);
      }
    });
  });
}

NOTE: I know mutable options are unwise.

FYI: I'm not sure, but in ReactiveCocoa, there is a same kind of functionality. -[RACSignal subscribe:] https://github.com/ReactiveCocoa/ReactiveCocoa/blob/1e97af8f5681b3685770eb30faf090e64c293290/ReactiveCocoaFramework/ReactiveCocoa/RACSignal.h#L115-L131

Upvotes: 0

Views: 51

Answers (1)

Bergi
Bergi

Reputation: 664237

Is there any better way?

Yes. .then(resolve, reject, notify); is the deferred antipattern.

Better chain the possibly-recursive call with an explicit then:

function myPromise(options) {
  return Q.Promise(function(resolve, reject, notify) {
    doSomthingAsync(options, function(resp) {
      // if (err) return reject(err);
      notify(resp);
      resolve(resp);
    });
  }).then(function(resp) {
    if (resp.nextPageToken) {
      options.pageToken = resp.nextPageToken;
      return myPromise(options);
    } else {
      return resp;
    }
  });
}

And instead of the new Q.Promise call you likely might be able to use one of the callback-function helper methods.

Upvotes: 1

Related Questions