Skip to content

Instantly share code, notes, and snippets.

@goenning
Created February 23, 2016 18:52
Show Gist options
  • Save goenning/19517a4c5a29bf481a62 to your computer and use it in GitHub Desktop.
Save goenning/19517a4c5a29bf481a62 to your computer and use it in GitHub Desktop.
sequential, parallel and pooled Promise resolving
import * as request from 'request'
import * as $ from 'cheerio'
let PromisePool = require("es6-promise-pool") //no typings definition
var sites = [
'http://www.microsoft.com',
'http://www.apple.com',
'http://stackoverflow.com',
'https://github.com'
]
var getBody = (site: string): Promise<string> => {
return new Promise((resolve, reject) => {
console.log(`Requesting: ${site}...`)
request.get(site, (error, response, body) => {
console.log(`Done: ${site}...`)
if (error)
reject(error)
resolve(body)
})
})
}
var sequential = (async () => {
for (let site of sites) {
var body = await getBody(site)
console.log(site, $("title", body).text())
}
})
var parallel = (async () => {
var result = await Promise.all(sites.map(getBody))
for (let i = 0; i < result.length; i++) {
console.log(sites[i], $("title", result[i]).text())
}
})
var pooled = (async () => {
let i = -1
let pool = new PromisePool(() => {
if (sites.length > ++i) {
return Promise.all([sites[i], getBody(sites[i])])
}
return null
}, 5)
pool.addEventListener('fulfilled', function(event) {
console.log(event.data.result[0], $("title", event.data.result[1]).text())
})
pool.addEventListener('rejected', function(event) {
console.log('Rejected', event.data.error)
})
await pool.start()
})
let timer = function(name) {
let start = new Date();
return {
stop: function() {
var end = new Date();
var time = end.getTime() - start.getTime();
return time;
}
}
};
var go = (async () => {
let result: any = {}
let seq = timer('Sequential')
await sequential()
result.sequential = seq.stop();
let par = timer('Parallel')
await parallel()
result.parallel = par.stop();
let pol = timer('Pooled')
await pooled()
result.pooled = pol.stop();
console.log(result)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment