Dmitriy Pavlov
Dmitriy Pavlov

Reputation: 23

How to breaking a for loop inside a callback function Node JS

please help!

How to breaking if available true?

I use node js tcp-ping module.

My code

var tcpp = require('tcp-ping');

    let arr = ['imap:143', 'imap:993', 'mail:143', 'mail:993'];

    for (let i = 0; i < arr.length; ++i) {

        let alias = arr[i].split(":")[0];
        let port = arr[i].split(":")[1];
        
        tcpp.probe(alias+'.aol.com', parseInt(port), function(err, available) {
            if(available){
                //need break
            }
        });

    }

Upvotes: 2

Views: 173

Answers (2)

jfriend00
jfriend00

Reputation: 707326

If you really want to send the probes one at a time, wait to see if you got the right response and if so, stop and if not, go to the next, then it's easiest to use await and promises like this:

const tcpp = require('tcp-ping');
const { promisify } = require('util');
const tcpp_probe = promisify(tcpp.probe);

async function probe(arr) {
    for (const item of arr) {
        const [alias, port] = item.split(":");
        try {
            const available = await tcpp_probe(alias + '.aol.com', parseInt(port));
            if (available) {
                // return whatever you want or act on the result here
                return alias;
            }
        } catch (e) {
            // decide what to do here if you get an error
            // this will log the error and then continue with the loop
            console.log(e);
        }
    }
    // no matches
    return null;
}

And, then you would call it like this:

let arr = ['imap:143', 'imap:993', 'mail:143', 'mail:993'];
probe(arr).then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

Upvotes: 1

Hyetigran
Hyetigran

Reputation: 1215

If you can't use async/await or promises, you could try calling your function recursively.

var probeAll = function(index, callback, err, available){
    // Terminal Condition
    if (available){
        // do something
        callback(available);
        return;
    }
    let arr = ['imap:143', 'imap:993', 'mail:143', 'mail:993'];
    let alias = arr[index].split(":")[0];
    let port = arr[index].split(":")[1];
    
    tcpp.probe(alias+'.aol.com', parseInt(port), function(err, available){
        probeAll(index++, callback, err, available);
    });
};

// First probeAll call
probeAll(0, function(avail){
    // Do something
});

Edit: you very well may need to tweak this to handle errors i.e. if none of the calls come back available, etc.

Upvotes: 0

Related Questions