-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyieldPromises.js
More file actions
26 lines (23 loc) · 892 Bytes
/
Copy pathyieldPromises.js
File metadata and controls
26 lines (23 loc) · 892 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Naive implementation of Promise.coroutine for learning purposes
const coroutine = generatorFunction => () => {
const generator = generatorFunction();
const processYieldObject = yieldObject => {
if (!yieldObject.done) {
const promise = yieldObject.value;
promise.then(response => processYieldObject(generator.next(response)));
}
}
processYieldObject(generator.next());
};
// Returns whatever args you pass to the second invocation after `duration` milliseconds
const delay = duration => (...args) => new Promise((resolve, reject) =>
setTimeout(() => resolve(...args), duration));
// Example usage (async code that looks synchronous)
const print = coroutine(function* () {
const hello = yield delay(500)('hello');
console.log(hello);
const goodbye = yield delay(500)('goodbye');
console.log(goodbye);
});
print();
console.log('See? It kept going.');