Изобретаем Deferred по новой
class Deferred {
constructor(generator) {
this.promise = new Promise((resolve, reject) => {
Object.assign(this, {resolve, reject});
});
generator.next();
let next = value => {
let result = generator.next(value);
if (!result.done) {
value = result.value;
if (value && value.next) {
new Deferred(value).done(next).fail(this.reject);
} else {
next(value);
}
}
};
next(this);
}
done(onFulfilled) {
this.promise.then(onFulfilled);
return this;
}
fail(onRejected) {
this.promise.catch(onRejected);
return this;
}
}
function * getFoo() {
let deferred = yield;
setTimeout(function() {
deferred.resolve('foo');
}, 100);
}
function * getBar() {
let deferred = yield;
let foo = yield getFoo();
setTimeout(function() {
deferred.resolve(foo + 'bar');
}, 100);
}
new Deferred(getBar()).done(function(value) {
console.log(value);
});
// в консоль выведется "foobar"