如何在回调函数Node JS中打破for循环

德米特里·帕夫洛夫(Dmitriy Pavlov)

请帮忙!

如果可用,该如何破译?

我使用node js tcp-ping模块。

我的密码

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
            }
        });

    }
jfriend00

如果您确实确实想一次发送一个探针,请等待看看您是否获得了正确的响应;如果是,请停止,如果没有,请转到下一个,那么它是最简单的使用方法,await并承诺如下:

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;
}

然后,您将这样称呼它:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章