2

I have an array like this:

var subscriptions = ['sub_1234', 'sub_5678', 'sub_8493'];

In my real application the array usually has about 800 subscription ids.

Currently I have a loop like this:

var subscriptionData = [];
for(var i in subscriptions) {
  subscriptionID = subscriptions[i];
  var data = await stripe.subscriptions.retrieve(subscriptionID);
  subscriptionData.push(data);
}

The purpose of the loop is to extrapolate the subscription ids to find out all of the information related to that id (payment amounts, invoices, etc.)

The problem is with 600 subscriptions it can take 20-30 minutes to go through all of that data.

Is there away to run the for loop in parallel so that it pulls all of the stripe subscriptions at once and pushes the data onto the array? Then continues?

I was looking at this library: https://github.com/caolan/async

But I couldn't figure out how to get it to do it if you don't know how long the array is (the array can be of variable length)

7
  • 1
    you should probably re-think how you're handling that many requests. Might want to send the API 1 request with all the ID's instead of 1 at a time Commented Sep 10, 2018 at 19:37
  • @Derek I was thinking that but couldn't figure out how to do it in Stripe, it only allows grabbing the details of 1 subscription at a time. Commented Sep 10, 2018 at 19:39
  • 1
    You can retrieve 10 or 20 subscriptions at the same time and await for them using Promise.all Commented Sep 10, 2018 at 19:57
  • 1
    There's a difference between async and parallel. To run anything in true parallel with Node, you need to use child processes. However, you can use Promise.all to launch simultaneous API calls like fxgx suggested, if that's what you need Commented Sep 10, 2018 at 20:31
  • @dpopp07 Can you provide examples using an array like the example? I can't find any Promise.all() examples with an array like that. Commented Sep 10, 2018 at 23:53

1 Answer 1

4
const subscriptions = ['sub_1234', 'sub_5678', 'sub_8493'];


async function customFunction(subscriptions) {

  const getSubscription = subscriptions.map((item) => {
    return stripe.subscriptions.retrieve(item);
  });

  const subscriptionData = await Promise.all(getSubscription);

  return subscriptionData; // returns an array
};


// call the function and pass parameter value

customFunction(subscriptions);
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to run a request like this in chunks of 10 at a time? I keep getting errors related to too many concurrent requests.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.