Unable to return correct value inside a pm.sendRequest

Hey community! I have the following code:

function validateDocumentMessage(expectedDocumentMessage) {
    var hasLegalStatusMessage = false;

    for (let retriesCount = 0; retriesCount < 5; retriesCount++) {

        var token = pm.environment.get('token')
        var urltf = pm.environment.get('url')
        var receiptId = pm.collectionVariables.get('receipt')

        var payload = {
            url: urltf + '/receipts/' + receiptId,
            method: 'GET',
            header: ['X-Invoiceware-Token: ' + token, 'Content-Type: application/json', 'Accept: application/json']
        }

        pm.sendRequest(payload, function (err, res) {
            var messages = res.json().Messages

            for (var x = 0; x < messages.length; x++) {
                if (messages[x].Description == expectedDocumentMessage) {
                    hasLegalStatusMessage = true;
                }
            }
        })

        sleep(1000);

    }
    
    return hasLegalStatusMessage;

}


function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}

The idea here is that for every 1 second up until 5 tries, I’ll send a request to an endpoint checking if a message is there. On line 21 I’m assigning True to the hasLegalStatusMessage, however when I return this variable at the end of the function (line 30), it`s returning False.

Could someone help me to identify why, and how I can return the correct value for this variable?

Hello @felipe.pazinatto

I wonder whether the if statement meets its conditions in order to set hasLegalStatusMessage to true.

Can you add a console.log inside that if statement to see whether you reach that point of your code?

You can then open Postman’s console after sending the request to see if you’re reaching it.

Hey @security-cosmologist

Thanks, actually it does assign a True to the hasLegalStatusMessage, however the function still returns false at line 30. I wonder if I should be assigning the variable in a distinct way?

Hi @felipe.pazinatto
I took another look, and I believe the issue here might be the fact that pm.sendRequest is asynchronous, hence your script returns hasLegalStatusMessage before it is set to false.

Can you try console logging hasLegalStatusMessage both before the return and inside the if statement, and see which one gets executed first?

I think the sleep function might be causing the issue here.

Can you try making your function async

and then add the following line instead of sleep before return

await new Promise(r => setTimeout(r, 2000));

To be fair that’s arguably an elegant or scalable solution, but it might unblock you

1 Like

Followed your suggestion @security-cosmologist , and it`s actually returning the hasLegalStatusMessage first (line 30), before assigning True to it (line 21).

I then did follow your approach, but now the code from the return is not executing. Here`s the entire method:

async function validateDocumentMessage(expectedDocumentMessage) {
    var hasLegalStatusMessage = false;

    for (let retriesCount = 0; retriesCount < 5; retriesCount++) {

        var token = pm.environment.get('tf.api.token')
        var urltf = pm.environment.get('tf.api.url')
        var receiptId = pm.collectionVariables.get('cfdiStandardReceipt')

        var payload = {
            url: urltf + '/receipts/' + receiptId,
            method: 'GET',
            header: ['X-Invoiceware-Token: ' + token, 'Content-Type: application/json', 'Accept: application/json']
        }

        pm.sendRequest(payload, function (err, res) {
            var messages = res.json().Messages

            for (var x = 0; x < messages.length; x++) {
                if (messages[x].Description == expectedDocumentMessage) {
                    hasLegalStatusMessage = true;
                    console.log("IF here")
                    console.log(hasLegalStatusMessage);
                }
            }
        })
        await new Promise(r => setTimeout(r, 1000));

    }
    console.log("return here")
    console.log(hasLegalStatusMessage)
    return hasLegalStatusMessage;
}