Skip to content

Instantly share code, notes, and snippets.

@talkol
Last active November 11, 2016 16:07
Show Gist options
  • Select an option

  • Save talkol/9f55a57860181cfd777752ba046ed5cf to your computer and use it in GitHub Desktop.

Select an option

Save talkol/9f55a57860181cfd777752ba046ed5cf to your computer and use it in GitHub Desktop.
import _ from 'lodash';
import fetch from 'node-fetch';
import delay from 'delay';
export function pingServers(servers) {
return _.reduce(servers, (failedServersAccumulator, url) => {
return failedServersAccumulator.then((failedServers) => {
return pingOneServer(url).then((failures) => {
if (failures > 0) failedServers[url] = failures;
return failedServers;
});
});
}, Promise.resolve({}));
}
function pingOneServer(url) {
return _.reduce(_.range(3), (failuresAccumulator) => {
return failuresAccumulator.then(delay(10000)).then((failures) => {
return fetch(url).then((response) => {
return response.ok ? failures : failures + 1;
});
});
}, Promise.resolve(0));
}
@DanielHreben
Copy link
Copy Markdown

DanielHreben commented Nov 11, 2016

Serial execution is not a promises strong side, most tasks must be executed in parallel, so usually we need just Promise.all(...).
But that sample can also looks better:

import fetch from 'node-fetch';
import delay from 'delay';

export function pingServers(servers) {
  return servers.reduce((acc, server) => {
    for (let i = 0; i < 3; i++) {
      acc.push(server);
    }
    return acc;
  }, [])
  .reduce((acc, server) => {
    return acc
    .then(delay(1000))
    .then(() => fetch(server))
    .then(response => [...acc, response])
  }, Promise.resolve([]))
  .then(responses => responses.reduce((acc, {url, ok}) => {
    if (!acc[ url ]) {
      acc[ url ] = 0;
    }

    if (!ok) {
      acc[ url ]++;
    } 

    return acc;
  }, {}));
}

Using of promises sometimes requires different than usual for sync code approach.
Sure, this sample can be simplified with lodash, but it can be much more simplified with lodash-fp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment