1

In the below script I am trying to break the for loop once I get the status code as 200, but requests keep happening even after receiving status code 200.

var getLibraries = host+'webcontents/libraries';

pm.sendRequest(getLibraries, function (err, response) {
    var jsonData = response.json();
    var library_id;
    var statusCode;
    var length = jsonData.contents.length;

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

        library_id = jsonData.contents[i].id;
        var getMLSConfigURL = host+'/library/'+library_id;
        pm.sendRequest(getMLSConfigURL, function (err, response) {
           statusCode = response.code;
            if(statusCode == 200){
                var mlsConfigData = response.json();
                console.log('ID: ', mlsConfigData.id);
                pm.environment.set("MLSConfigLib_Id", mlsConfigData.id);
                return;
            }
        });
        if(statusCode == 200){
            break;
       }
    }
});
mangesh
  • 511
  • 8
  • 24
Ranjeet
  • 49
  • 8
  • Have you tried when `===` in the `if` statements? – Danny Dainton Jun 16 '20 at 09:36
  • I tried it is not working – Ranjeet Jun 16 '20 at 09:38
  • statusCode if statement is executed before `sentRequest` callback will set statusCode. Add console.log() to the end of the for-loop to see that statusCode is always undefined. If you console log statusCode in `sendRequest` you'll see that it executes after for-loop finished running. Read this article about node's event loop: https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c – Lukas C Jun 16 '20 at 09:48

1 Answers1

0

If you have the condition you want, set the "i' variable to the length amount (i = length) after the condition before the end of the FOR LOOP and it will stop the loop.