1
\$\begingroup\$

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))
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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))
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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