Last active
January 1, 2016 11:19
-
-
Save dbushong/8136945 to your computer and use it in GitHub Desktop.
Comparison of vanilla callback-passing vs. iced coffeescript vs. Q/promises. Mission is: 1. prompt for a url prefix
2. fetch (in parallel) two URLs based on that prefix
3. sleep for a number of seconds equal to the sum of the lengths of the results
4. print something announcing we're done
This file contains 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
request = require 'request' | |
prompt = (str, cb) -> # same as vanilla | |
in = process.stdin | |
process.stdout.write "#{str}: " | |
in.setEncoding 'utf8' | |
in.once 'error', cb | |
in.once 'data', (res) -> | |
in.pause() | |
cb null, res.trim() | |
in.resume() | |
await prompt 'Enter base URL', defer err, base | |
throw err if err? | |
await | |
request "#{base}/one", defer err1, res1, h1 | |
request "#{base}/two", defer err2, res2, h2 | |
throw err1 ? err2 if err1 ? err2 | |
await setTimeout defer(), (h1.length + h2.length) * 1000 | |
console.log 'done!' |
This file contains 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
Q = require 'q' | |
http = require 'q-io/http' | |
prompt = (str) -> | |
in = process.stdin | |
d = Q.defer() | |
process.stdout.write "#{str}: " | |
in.setEncoding 'utf8' | |
in.once 'error', d.reject.bind d | |
in.once 'data', (res) -> | |
in.pause() | |
d.resolve res.trim() | |
in.resume() | |
d.promise | |
prompt('Enter base URL') | |
.then (base) -> | |
['one', 'two'].map (p) -> http.read("#{base}/#{p}") | |
.all() | |
.spread (h1, h2) -> | |
Q.delay (h1.length + h2.length)*1000 | |
.then -> | |
console.log 'done!' | |
.done() |
This file contains 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
request = require 'request' | |
async = require 'async' | |
prompt = (str, cb) -> # same as iced | |
in = process.stdin | |
process.stdout.write "#{str}: " | |
in.setEncoding 'utf8' | |
in.once 'error', cb | |
in.once 'data', (res) -> | |
in.pause() | |
cb null, res.trim() | |
in.resume() | |
prompt 'Enter base URL', (err, base) -> | |
throw err if err? | |
fetch = (p, cb) -> request "#{base}/#{p}", (err, res, body) -> cb err, body | |
async.map ['one', 'two'], fetch, (err, htmls) -> | |
throw err if err? | |
[h1, h2] = htmls | |
setTimeout (-> console.log 'done!'), (h1.length + h2.length) * 1000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment