I have done this a few times. The key is to have the first request use a synchronous call so it executes to completion and then the use the data from that call to make the second request.
Part 1: setup the first API call. I had a need to call an API several times to get the data I needed for the second call. This also works for a single call.
//
//Function to call each url in an array of urls
//
const requestAsync = function(url) {
return z.request(url).then((response) => response.json)
}
//
//Create the array of urls to call synchronously
//
var urlArr = [];
const urls = { url: 'https://your.api.com', method: 'GET',
headers: { 'Accept': 'application/json' },
params: { “name”: “myparameter” }
};
urlArr.push(urls);
PART 2: Call the first API synchronously
//
//Call the function for each item in the urlArr
//
return Promise.all(urlArr.map(requestAsync))
.then(function(values){
//Process the results of the first API Call
}
Part 3: Build the API options
const options = { url: 'https://your.api.com',
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: { “name”: “myparameter” },
body: {“name”: “MyBody” }
};
Part 4: Call the second API
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
if (response.status === 200) {
return {"response status": response.status};
} else {
return results;
}
}); //End of PUT
}) //End of Promise
.catch(function(err) {
z.console.log(err);
//throw new Error('SOMETHING WENT WRONG...');
})