Skip to content

Instantly share code, notes, and snippets.

@huytd
Last active May 25, 2016 10:10
Show Gist options
  • Save huytd/ae44fa2f83fc797b8f12da527ac1516c to your computer and use it in GitHub Desktop.
Save huytd/ae44fa2f83fc797b8f12da527ac1516c to your computer and use it in GitHub Desktop.
Re-implement tj/co in 15 lines
function run(fn) {
var pointer = fn();
var next = function(result) {
if (result.value.then && typeof result.value.then === 'function') {
result.value.then(function(data) {
var out = pointer.next(data);
if (!out.done) next(out);
});
} else {
var out = pointer.next(result.value);
if (!out.done) next(out);
}
}
next(pointer.next());
}
'use strict';
var request = require('superagent');
// Use case #1: Working with promises
run(function*() {
var result = (yield request.get('http://huytd.github.io/posts/hello.md')).text;
console.log('Case #1:', result);
});
// Output:
// Case #1: Hi! I'm Huy! Nice to meet you!
'use strict';
var request = require('superagent');
// Use case #2: Get the value directly
run(function*() {
var result = yield 100;
console.log('Case #2:', result, '\n');
});
// Output:
// Case #2: 100
'use strict';
var request = require('superagent');
// Use case #3: Multiple async calls
run(function*(){
var r1 = (yield request.get('http://huytd.github.io/posts/hello.md'));
var r2 = yield '8th May\n';
var r3 = (yield request.get('http://huytd.github.io/posts/hello.md'));
console.log('Case #3:\n');
console.log('> r1:', r1.text);
console.log('> r2:', r2);
console.log('> r3:', r3.text);
});
// Output:
// Case #3:
// > r1: Hi! I'm Huy! Nice to meet you!
// > r2: 8th May
// > r3: Hi! I'm Huy! Nice to meet you!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment