Last active
November 11, 2016 16:07
-
-
Save talkol/9f55a57860181cfd777752ba046ed5cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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 withlodash-fp.