Last active
October 25, 2018 11:05
-
-
Save lsongdev/f0a331f69a8319d11b92aeb77d07598c to your computer and use it in GitHub Desktop.
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 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)); |
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 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