-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcoroutine.js
38 lines (32 loc) · 947 Bytes
/
coroutine.js
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
27
28
29
30
31
32
33
34
35
36
37
38
const coroutine = function(generatorFunction) {
const promise = defer();
const generator = generatorFunction();
next();
return promise;
// Call next() or throw() on the generator as necessary
function next(value, isError) {
const response = isError ?
generator.throw(value) : generator.next(value);
if (response.done) {
return promise.resolve(response);
}
handleAsync(response.value);
}
// Handle the result the generator yielded
function handleAsync(async) {
if (async && async.then) {
handlePromise(async);
} else if (typeof async === 'function') {
var v = async();
next(v);
} else if (async === undefined) {
setTimeout(next, 0);
} else {
next(new Error(`Invalid yield ${async}`), true);
}
}
// If the generator yielded a promise, call `.then()`
function handlePromise(async) {
async.then(next, (error) => next(error, true));
}
};