pm.sendRequest is working after the for loop iteration is completed even though the request is inside the loop

I’m trying to trigger a “pm.sendRequest” inside a for loop and the request is getting sent only after the iteration is completed, though I have kept the request inside the loop.

My Test look like,

for (i=0;i<5;i++)
{
    const requestObject = {
    url: 'https://reqres.in/api/users?page=2',
    method: 'GET',
    header: 'Content-Type:application/json',

}
        console.log(i)
pm.sendRequest(requestObject, (err, res) => {
        console.log(i)

})}

The "i" which is getting printed inside the pm.sendRequest is alwas printed as 5.

Could you please help me in resolving this issue.

Hi @VasanthPasupathi! Welcome to the community :tada:

Using Postman Echo as an example, the following worked for me.

for (var i=0; i<5; i++) {

    const reqObj = {
        'url': `https://postman-echo.com/get?foo=${i}`,
        'method': 'GET'
    }
    pm.sendRequest(reqObj, (err, res) => {
        if (err) {
            console.log(err)
        } else {
            console.log(res.json().args.foo)
        }
    })
    console.log(i)
}

This returns:
Screen Shot 2021-02-08 at 4.26.21 pm

Hope this helps!
Let me know if you have further questions!

Hi @taehoshino ,
The iteration is not running proper if you could see your screenshot the iteration is 0,1,3,2,4 and not 0,1,2,3,4.

Also I want the I to be printed inside the if or else block if you try doing that you’ll be getting only the last value of ‘i’ printed

I know what you mean :+1:
That’s because the pm.sendRequest is asynchronous function and by the time res is returned from pm.sendRequest call, the value of i is already proceeded to the last value.

If you want to show value of i corresponding to each request, you can use Promise, e.g.:

const sendReq = (i) => {
    const reqObj = {
        'url': `https://postman-echo.com/get?foo=${i}`,
        'method': 'GET'
    }
    return new Promise((resolve, reject) => {
        pm.sendRequest(reqObj, (err, res) => {
            if (err) {
                reject(err)
            } else {
                resolve(i)
            }
        })
    })
}

for (var i=0; i<5; i++) {
    sendReq(i).then((res) => {
        console.log(res)
    })
}

But again, console.log(res) in for loop is only printed after the response is returned, so it is not necessarily the numerical order.

Hope this clarifies a bit :upside_down_face:

1 Like

Sorry to dig up the subject, but it does not answer the question, or I’m wrong it does not refer that the first iterait

Can you please give an example when I want the FOR loop to wait for “sendReq” before sending the next “sendReq”?
In this case it will wait before “console.log”, but the 2nd request may be still executed before “console.log” of the 1st request.