Last active
August 29, 2015 14:23
-
-
Save hekike/369f611646171b5facd2 to your computer and use it in GitHub Desktop.
co "re-impelented"
This file contains 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
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); | |
}); |
This file contains 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
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