Asynchronous Pre-Request script in #Postman

A Pre-request script in Postman allows you to dynamically change the request body based on any JavaScript function you provide, this sometimes is done to dynamically calculate HMACs in the request, such that you don’t have to manually calculate it before every request.

However, it’s not obvious how to create an asynchronous pre-request script, that is one that does not return instantly, but has to wait for some external factor (i.e. a HTTP Request), before completing the main request.

Here is the simple example, where we want to inject the user’s IP address into the HTTP request body before sending; as follows –

new Promise(resolve =>

pm.sendRequest(“http://checkip.amazonaws.com/”,function(e, r){
pm.request.body.update(JSON.stringify(r.text()));
resolve();
})

);

And, the main request will not execute until the promise returned in the pre-request script is resolved.

Leave a Reply

Your email address will not be published. Required fields are marked *