Skip to content

Instantly share code, notes, and snippets.

@hekike
Last active August 29, 2015 14:23
Show Gist options
  • Save hekike/369f611646171b5facd2 to your computer and use it in GitHub Desktop.
Save hekike/369f611646171b5facd2 to your computer and use it in GitHub Desktop.
co "re-impelented"
function asyncCalc (num, delay) {
delay = delay || 500;
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(num);
}, delay);
});
}
run(function* () {
var a = yield 4;
var b = yield asyncCalc(50, 500);
var c = yield [
asyncCalc(50, 500),
asyncCalc(50, 200)
];
return {
sum: a + b + c[0] + c[1]
};
})
.then(function (result) {
console.log(result);
});
function run (fn) {
var iterator = fn();
return new Promise(function (resolve, reject) {
function next (result) {
if (result.done) {
resolve(result.value);
return;
}
// is promise
if (typeof result.value.then === 'function') {
result.value.then(function (res) {
next(iterator.next(res));
}).catch(reject);
}
// is array of promise -> paralell
else if (Array.isArray(result.value)) {
Promise.all(result.value).then(function (res) {
next(iterator.next(res));
}).catch(reject);
}
else {
next(iterator.next(result.value));
}
}
next(iterator.next());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment