Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Does this make sense? How would you achieve the same thing, with cleaner code?

function retrieveBatch(offset){
  var opts = {}
  opts.limit = 100
  if(offset) opts.offset = offset
  return new Promise(function(resolve, reject) {
    chargebee.subscription
    .list(opts)
    .request(function(err, value){
      if(err) return reject(err)
      return resolve(value)
    })
  })
}

function retireveAll(){
  var subscriptions = []
  function inception(data){
    if(!data) return retrieveBatch().then(inception)
    if(data && data.list) subscriptions.push(data.list)
    if(data && data.next_offset) return retrieveBatch(data.next_offset).then(inception)
    if(data && !data.next_offset) return _.flatten(subscriptions)
  }
  return Promise.resolve(inception(false))
}
share|improve this question

1 Answer 1

I only have some minor additions, maybe a little syntax sugar. I've tested most of it in the JavaScript console, and it still needs at least some JSBin trials before going live.

function retrieveBatch(offset){
  var opts = {
    limit  : 100,
    offset : offset || undefined
  };

  return new Promise(function(resolve, reject){
    chargebee.subscription
      .list(opts)
      .request(function(err, value){
        // return only if err is defined
        err && return reject(err);
        // if you got this far, there's only one way out
        return resolve(value);
      })
  })
}

function retrieveAll(){
  var subscriptions = [];

  function inception(data){
    if(!data){
      return retrieveBatch().then(inception);
    }
    if(data.list){
      subscriptions.push(data.list);
    }
    if(data.next_offset){
      return retrieveBatch(data.next_offset).then(inception);
    }

    return _.flatten(subscriptions);
  }
  return Promise.resolve(inception(false))
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.