Home > Enterprise >  Best practice to send multiple POST API request in foreach
Best practice to send multiple POST API request in foreach

Time:08-13

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

CodePudding user response:

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);

CodePudding user response:

One of the approach is using Promises in parallel

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

let result = await Promises.allsettled(promises).then((result) => ....).catch(error);

Also If you request are not dependent on each other and you do not want to stop execution when any of the request fails, you can use Promise.allsettled

Promise.all will reject as soon as one of the Promises in the array rejects.

Promise.allSettled will never reject - it will resolve once all Promises in the array have either rejected or resolved.

  • Related