gpt4 book ai didi

Javascript - 如何使 ping 结果始终按照数组变量的原点顺序

转载 作者:行者123 更新时间:2023-12-01 02:24:07 25 4
gpt4 key购买 nike

我想根据数组变量的起源始终按顺序获得 ping 结果。

代码来源于here

这是代码:

var ping = require ('net-ping');

var targets = ['8.8.8.8','8.8.4.4'];

var session = ping.createSession();

for (var i = 0; i < targets.length; i++) {
session.pingHost (targets[i], function (error, target, sent, rcvd) {
var ms = rcvd - sent;
if (error) {
if (error instanceof ping.RequestTimedOutError) {
target;
} else {
error.toString ();
}
} else {
var result = target + ": " + ms + " ms";
console.log(result);
}
});
}

如果我运行代码三次,结果是:

// first
8.8.8.8: 6 ms
8.8.4.4: 8 ms

// second
8.8.4.4: 7 ms <- // the list of ip address is not sequential
8.8.8.8: 10 ms <- // not like the first and third result

// third
8.8.8.8: 5 ms
8.8.4.4: 9 ms

我认为 ping 结果是以 ms(毫秒)为单位的最小值将首先显示,但是如何使结果始终像数组变量的起源一样连续显示 var Targets = ['8.8.8.8','8.8. 4.4']

也许我必须将结果放入数组并使其按顺序排列,但我不知道该怎么做。

有人可以帮助我吗?

最佳答案

Promise 让这变得非常简单

Promise.all(targets.map(tgt => 
new Promise(resolve =>
session.pingHost(tgt, (error, target, sent, rcvd) =>
resolve({error, target, sent, rcvd})
// resolves to an object containing all the arguments in the callback
// note: always resolve, even for error - so promise.all can work for you
)
)
)).then(results => {
// results array, same order as targets array
// process all the results here
results.forEach(({error, target, sent, rcvd}) => {
// here are all the original arguments in the callback for pingHost resolved above
// all the "logic" you perform in the pingHost callback in your code can be done here, and this is after all results are in
}
});

如果你愿意,我可以发布不使用 Promises 的代码,但由于你使用的是 Nodejs,所以请使用 Promises :p

关于Javascript - 如何使 ping 结果始终按照数组变量的原点顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48958374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com