Can I send 2 or more request in the pre-request script with a delay between them?

I’d like to run 2 requests in the pre-request script, both are to generate an admin csrf token, I don’t want to duplicate them in every single test folder within several collections so I set up both request in the Collection and then call them in a “Create User” endpoint that requires admin rights, so far I’ve tried adding a setTimeout for both like this:

const logInPage = pm.collectionVariables.get("logInPage")

const adminLogInAction = pm.collectionVariables.get("adminLogInAction")

setTimeout(loginPageReq, 3000);

setTimeout(adminRequest, 5000);

function loginPageReq() {

pm.sendRequest(logInPage, function(err, response){

const $ = cheerio.load(response.text());

let csrfToken = $('[name=_csrf]').attr('value');

pm.globals.set("csrfToken", csrfToken);

})

};

function adminRequest() {

pm.sendRequest(adminLogInAction, function(err, response){

const $ = cheerio.load(response.text());

    if ($('[csrf-header-name="X-CSRF-TOKEN"]').attr('csrf-token')){

        const csrfToken = $('[csrf-header-name="X-CSRF-TOKEN"]').attr('csrf-token');

        pm.globals.set("csrfToken", csrfToken);

    } else {

        const csrfToken = $('[name="_csrf"]').val();

        pm.globals.set("csrfToken", csrfToken);

    }

})

};

I’d like to run loginPageReq, wait 3 seconds and then run adminRequest, before running the CreateUser request.
Actual result: it waits 5 seconds, then executes both

{
    pm.sendRequest("https://postman-echo.com/get", function (err, response) {
     
        setTimeout( function(){pm.sendRequest("https://reqres.in/api/users", function (err, response) {
            console.log(response.json());
        })},3000)
    });
}

You should chain the request like this , now first request will be send and then it waits 3 sec to call the next request

if just called set time out , then both set timeout will be called at the same time , and first request will be made after 3sec and then after 2sec second request will be called .

1 Like

in your case it can also be done as :

setTimeout(loginPageReq, 0);

setTimeout(adminRequest, 3000); 

but this doesn’t guarantee that second request is send after you get response from first request

For some reason, this didn’t make it run synchronously, I’m about to try Promises, if I get a positive result, I’ll post the solution.

I was able to resolve it, but it was a different problem, I created the variable for adminLogInAction incorrectly, it was failing because of that and not because the calls didn’t run synchrounously. Thanks @praveendvd your suggestion helped me out anyway.