Skip to content
Advertisement

Best practice to send multiple POST API request in foreach

I need to create multiple Google Analytics properties programmatically using the GA Admin API – https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/properties/create.

It is about 300+ properties so also 300+ post requests with different request bodies. For that, I have an array with those 300+ objects. What would be the best practice in JS to perform all these requests? Can I just loop the array with forEach and use the fetch function in each iteration?

propertyArr.forEach((e, i, a) => {
    gapi.client.request({ 
        path: 'https://analyticsadmin.googleapis.com/v1beta/properties', 
        method: 'POST', 
        body: e
    });
});

This is what I have right now. Note I am using gapi.client.request() method to make the call.

Thank you

Advertisement

Answer

You can map over propertyArr and use Promises.allsettled to ensure all requests are either rejected/resolved

const allRequests = propertyArr.map((e, i, a) => {
   return gapi.client.request({ 
       path: 'https://analyticsadmin.googleapis.com/v1beta/properties', 
       method: 'POST', 
       body: e
   });
});
let result = await Promises.allsettled(allRequests ).then(success).catch(error);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement