Pre-request async code doesn't wait for execution


One of my requirement is to call an async login API as a pre-request script in Postman windows client. Through this code I want to set the collection variable (jwt-token). The problem is that Postman doesn’t wait for the completion of the pre-request call and hence the actual request is throwing an error of ‘Un-authorized access’.

Below is the code:

(async ()=>{
const loginRequest = {
method: ‘POST’,
url: pm.collectionVariables.get(“loginUrl”),
header: {
‘Content-Type’: ‘application/json’
raw: JSON.stringify({ email: “”, password: “”})
await pm.sendRequest(loginRequest,(error, response)=>{
pm.collectionVariables.set(“jwt-token”, response.token)

Hey @ahussain.ned , welcome to the Postman community!

I’d recommend having a look at this collection, it has examples of different ways to handle async operations and making sure things execute before the request goes through:

You can also fork the collection and try it out for yourself.

Late, but since no one actually answered your question I’ll go ahead as I just got done feeling your pain.

The problem here is for whatever reason pm.sendRequest returns a function rather than a Promise.

The execution environment does have a scan that detects top-level Promises though, so the solution is to wrap your async work in a Promise and call the resolve function like you would a termination signal in older unit testing frameworks:

new Promise((res) => pm.sendRequest(
  {... your config },
  (err, res) => {
      ... your code

The documentation, DX, ergonomics around scripting and automation in this product could definitely use some love.