I did not examine ES6 generators in depth, but the generator passed its own .next another function, since the callback is not suitable for me. In any case, this can create a situation in which readSensor fails, and you have no way to deal with this failure, ultimately in a dead end.
I suggest changing or wrapping readSensor to return a promise, and then use the technique described in this article .
This will allow you to write such code (verified in Node v0.12.0):
var Promise = require('q'); var main = async(function* () { var reading = yield readSensor(); console.log(reading); reading = yield readSensor(); console.log(reading); }); main(); function readSensor() { return Promise.delay(2000).thenResolve(Math.random() * 100); } function async(makeGenerator){ return function () { var generator = makeGenerator.apply(this, arguments); function handle(result){
As a note, loganfsmyth below Q already provides the Q.async() method, which provides the functionality of this async() function, and possibly other promise libraries.
source share