I'm working with a modified version of this example for writing a helper for vaguely async
/await
syntax. Here's the code in TypeScript:
export class Async {
public static do(makeGenerator) {
let generator = makeGenerator.apply(this, arguments);
try {
return handle(generator.next());
} catch (error) {
return Promise.reject(error);
}
function handle(result) {
if (result.done) {
return Promise.resolve(result.value);
}
return Promise.resolve(result.value)
.then(nextResult => {
return handle(generator.next(nextResult));
})
.catch(error => {
return handle(generator.throw(error));
});
}
}
}
The usage is meant to be like:
Async.do(function* () {
let someResult = yield somePromise();
// Don't continue until the promise resolves
someDependentOperation(someResult);
});
That all works just fine.
Where it falls down is if I try to return Async.do(...)
. I'd thought from inspecting the code that this should return a Promise
object, but this apparently isn't the case. Async.do
returns immediately, and the result is undefined
. Is there something I'm missing about the way generators work?