How to wait for an async pm.sendRequest to complete?

Hi there,

I`m testing an API for which I POST a document, then need to check for the confirmation messages generated, this is the 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);
}

What I`m trying to achieve is that once I call this method, I should check if the message is there, every second as per loop. If found, it should break out of the loop and return the hasLegalStatusMessage value.

However the return is actually returning the hasLegalStatusMessage before the pm.sendRequest completes, meaning I`m getting false instead of true. Given that, I have the following questions:

-How do I break the loop in Postman? I tried using break, but didn`t work;
-Is there an easy way to make sure that the return will only be executed after the GET request completes?

2 Likes