I am making 3rd party API calls in order to save and use the registered user details to create records on each one of the API platforms. In order to do that, I need to fetch the data from one API call and use that data (a property of the data) to make the next API call in Nodejs. For this, I am using fetch() along with Promise as shown in the code sample below.
// Call the API
fetch('url1').then(function (response) {
if (!response.ok) return Promise.reject(response);
return response.json();
}).then(function (url1Response) {
// Store the url1 response data to a variable for futher use (if required)
newdata = url1Response;
return fetch('url2'); // use a property of the first api response to execute next API call.
}).then(function (response) {
if (!response.ok) return Promise.reject(response);
return response.json();
}).then(function (url2Response) {
console.log(newdata, url1Response);
}).catch(function (error) {
console.warn(error);
});
My code execution is working but it is taking too long time to execute and send the response at last, So I want to optimize the time for execution.
Is there any way to do to execute this in a very optimized way so that the time complexity will be as minimum as possible? It will be great if any node module is there to solve this.