2
\$\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))
}
asked Feb 16, 2015 at 18:03
\$\endgroup\$

1 Answer 1

2
\$\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))
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Mar 31, 2015 at 21:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.