How to send Synchronous sendRequest calls


I am trying to use the sendRequest in the tests.
Here I am getting the some data from API,
and trying to delete it using another API.
For delete request, I need a token for which I need another API.
Below code is working fine and sometimes it is not working due to the reason there is already a request trying to process.
I have added timeout as well but that is not helping much

pm.test("Status code is 202", function authenticate() {
	const postRequest = createGetTimersRequest();
	pm.sendRequest(postRequest, (error, response) => {
			var jsonData = response.json();
			if (jsonData.departureTimerSetting.timers.length > 0) {
				jsonData.departureTimerSetting.timers.forEach(function(timer) {
					const tokenRequest = createRequest("XX", "XXXX");
					setTimeout(function() {
						pm.sendRequest(tokenRequest, (error, tokenResponse) => {
								var tokenData = tokenResponse.json();
								const timerDelete = createDeleteTimersRequest(timer.timerIndex, tokenData.token);
								setTimeout(function() {
									pm.sendRequest(timerDelete, function(err, res) {
											pm.test("Status code is 200", () => {
												setTimeout(function() {}, 1000);
								}, 2000);	
					}, 4000);

I have resolved it by sending only one request.
I constructed json object based on the count, I got in the response and that json object directly in one request

Hey @ereddy068 ! Glad you were able to solve it on your own, for future references you can have a look at this collections which showcases multiple ways to do async calls in pre-request scripts without using timeouts:

Also please mark your answer as the solution. :slightly_smiling_face:

For the question posed, I’m not quite understanding why this couldn’t just be a folder, with the three requests in order.

The initial GET request, then the TOKEN request, and finally the DELETE request, passing the values between the requests with collection or environment variables.

I am having a folder and set of requests it.
Now there are 2 requests in the folder which are going to create new data into the system.
When calling those endpoints, prerequisite is to clear the existing data and create new data.
This will help us to have the constant data while doing some validation
If in case the data is not deleted then during the validation, count will fail and also we can’t guarantee the data to be in the expected order

Above 3 sendrequests will help us to delete all old data and keep test cases success

1 Like