简体   繁体   中英

Sort a list of servers by fastest ping time with Javascript

In my Electron app I have a list of server addresses that I need to sort by shortest response time. I have a function that needs the sorted list:

function start() {
    // first step, get list of servers
    var servers_sorted = get_sorted_list_of_servers();

    // rest of function
}

Then I have a function that iterates through the list of servers:

function get_sorted_list_of_servers() {
    // access unsorted list from file

    unsorted_servers.forEach((server) => {
        // Get ping times for each server
        // Here is where I am stuck
    });

    // Sort based on ping times....

    return sorted_list_of_servers;
}

The problem is that I'm not sure how to get the ping time for each server. I've found a couple of libraries that wrap the ping utility ( net-ping and ping ). However, they use callbacks (which makes sense given that pinging a server can take a minute) and I need some way of getting a list of the server times.

// From ping example code
unsorted_servers.forEach(function (server) {
    ping.promise.probe(host).then(function (res) {
        console.log(res);
        // Update a global variable here??
    });
});

I've thought about letting the callbacks update a global list but then I need some way of signalling once all the servers have been tested.

Any guidance is appreciated. Thanks!

You can use Promise.all and map to loop over your server list and wait for all of the Promises to resolve. Here's a quick example using ping:

 const sortBy = require('lodash.sortby'); const ping = require('ping'); const servers = ['google.com', 'facebook.com', 'amazon.com', 'apple.com']; Promise.all(servers.map(server => ping.promise.probe(server))).then(response => { console.log(sortBy(response, 'time')) }); 

Here's an React demo using Promise.all and rendering the results:

https://server-ping-fuupenayzp.now.sh/

and the source

https://zeit.co/rusty-dev/server-ping/fuupenayzp/source?f=src/App.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM