Last active
February 8, 2016 17:08
-
-
Save nimbus154/c88f6f0f058fc9ec5005 to your computer and use it in GitHub Desktop.
Using & testing coroutines in Node.js with co & tape
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
const bluebird = require('bluebird'); | |
const co = require('co'); | |
const fs = bluebird.promisifyAll(require('fs')); | |
const _ = require('lodash'); | |
function lsPromise() { | |
return co(function* () { | |
let paths = { current: '.', root: '/' }; | |
return yield _.mapValues(paths, path => fs.readdirAsync(path)); | |
}); | |
} | |
function lsCallback(cb) { | |
cb = cb || () => {}; | |
return lsPromise() | |
.then(files => cb(null, files)) | |
.catch(e => cb(e)); | |
} | |
co(function* main() { | |
let files = yield lsPromise(); | |
console.log('promise', files); | |
}); | |
lsCallback((e, r) => { | |
if (e) | |
return console.log('error', e); | |
console.log('callback', r); | |
}) |
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
{ | |
"name": "coroutines", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"engines": { | |
"node": ">=4" | |
}, | |
"scripts": { | |
"start": "node --use_strict index", | |
"test": "node test" | |
}, | |
"author": "nimbus154", | |
"license": "MIT", | |
"dependencies": { | |
"bluebird": "^3.2.2", | |
"co": "^4.6.0", | |
"lodash": "^4.2.1" | |
}, | |
"devDependencies": { | |
"blue-tape": "^0.2.0" | |
} | |
} |
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
const bluebird = require('bluebird'); | |
const test = require('blue-tape'); | |
const co = require('co'); | |
const fs = bluebird.promisifyAll(require('fs')); | |
function ls(path) { | |
return co(function* () { | |
return yield fs.readdirAsync(path); | |
}); | |
} | |
test('should exist', assert => { | |
return ls('.'); | |
}); | |
test('not exist', assert => { | |
return assert.shouldFail(ls('./not-a-directory')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment