Skip to content

Instantly share code, notes, and snippets.

@octatone
Last active August 29, 2015 14:08
Show Gist options
  • Save octatone/fd32d43d6a60f4fe960c to your computer and use it in GitHub Desktop.
Save octatone/fd32d43d6a60f4fe960c to your computer and use it in GitHub Desktop.
Co - working with arrays of generators
'use strict';
const request = require('request'),
promisify = require('es6-promisify'),
get = promisify(request.get),
co = require('co'),
okay = /^2/,
sites = [
'https://www.google.com',
'https://www.twitter.com',
'https://www.wikipedia.org',
'https://www.wunderlist.com',
'https://www.reddit.com'
];
function *ping (url) {
let response;
try {
response = yield get(url);
}
catch (e) {console.log(e.message);}
let up = isUp(response);
return [url, up];
}
function isUp (response) {
return response ? okay.test(response.statusCode) : false;
}
function logStatuses (statuses) {
statuses.forEach(function (tuple) {
console.log(tuple[0], tuple[1] === true ? 'up' : 'down');
});
}
function *checkSatusesParallel (sites) {
let then = Date.now();
let statuses = yield sites.map(ping);
console.log('parallel', Date.now() - then, 'ms');
logStatuses(statuses);
}
function *checkSatusesSequential (sites) {
let then = Date.now();
let statuses = [];
for (let site in sites) {
let status = yield ping(sites[site]);
statuses.push(status);
}
console.log('sequential ', Date.now() - then, 'ms');
logStatuses(statuses);
}
co(function *main () {
yield checkSatusesParallel(sites);
yield checkSatusesSequential(sites);
// You can also run both checks in parallel:
// yield [checkSatusesParallel(sites), checkSatusesSequential(sites)];
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment