Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Created May 1, 2016 16:59
Show Gist options
  • Select an option

  • Save eduardonunesp/5ec2afea5358a7c852e1a9c7ab78e184 to your computer and use it in GitHub Desktop.

Select an option

Save eduardonunesp/5ec2afea5358a7c852e1a9c7ab78e184 to your computer and use it in GitHub Desktop.
Mini CO
const log = function(args) {
args = Array.isArray(args) ? args : Array.prototype.slice.call(arguments)
console.log.apply(console, args);
};
const tOut = function(time) {
return new Promise(function(resolve) {
setTimeout(() => {
resolve(time);
}, time);
});
};
const f = co(function *() {
log('Ok');
const t1 = yield tOut(1000);
log('tOut1', t1);
const t2 = yield tOut(2000);
log('tOut2', 2000);
return 666;
}).then(function(res) {
log(res);
});
function co(gen) {
const ctx = this;
const args = Array.prototype.slice.call(arguments, 1);
return new Promise(function(resolve, reject) {
gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
function onFulfilled(res) {
let ret;
try {
ret = gen.next(res);
} catch(e) {
return reject(e);
}
next(ret);
return null;
}
function onRejected(err) {
let ret;
try {
ret = gen.throw(err);
} catch(e) {
return reject(e);
}
next(ret);
}
function next(ret) {
if (ret.done) return resolve(ret.value);
const value = ret.value;
return value.then(onFulfilled, onRejected);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment