Skip to content

Instantly share code, notes, and snippets.

@lsongdev
Last active October 25, 2018 11:05
Show Gist options
  • Save lsongdev/f0a331f69a8319d11b92aeb77d07598c to your computer and use it in GitHub Desktop.
Save lsongdev/f0a331f69a8319d11b92aeb77d07598c to your computer and use it in GitHub Desktop.
const sleep1 = (time = 1) => {
return fn => {
setTimeout(() => fn(null, time), time * 1000);
};
}
const sleep2 = (time = 1) => new Promise(resolve => {
setTimeout(() => resolve(time), time * 1000);
});
co(function* () {
const a = yield 1;
console.log('a = ', a);
const b = yield sleep1(2);
console.log('b = ', b);
const c = yield sleep2(3);
console.log('c = ', c);
return 4;
}).then(res => {
console.log('done', res);
}, err => console.error('error', err));
const co = (fn, ...args) => new Promise((resolve, reject) => {
if (typeof fn !== 'function')
return reject(new TypeError('must be a function'));
let value, done, gen = fn.apply(null, args);
(function next(v) {
try{
({ value, done } = gen.next(v));
}catch(e) {
return reject(e);
}
const _next = x => (done ? resolve : next)(x);
switch(true){
case (typeof value === 'function'):
value((err, result) => err ? reject(err) : _next(result)); // thunkify style
break;
case (typeof value === 'object' && typeof value.then === 'function'):
value.then(_next, reject); // thenable
break;
default: // otherwise
_next(value);
break;
}
})();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment