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?
JavaScript
x
8
1
propertyArr.forEach((e, i, a) => {
2
gapi.client.request({
3
path: 'https://analyticsadmin.googleapis.com/v1beta/properties',
4
method: 'POST',
5
body: e
6
});
7
});
8
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
JavaScript
1
9
1
const allRequests = propertyArr.map((e, i, a) => {
2
return gapi.client.request({
3
path: 'https://analyticsadmin.googleapis.com/v1beta/properties',
4
method: 'POST',
5
body: e
6
});
7
});
8
let result = await Promises.allsettled(allRequests ).then(success).catch(error);
9