我读过,生成器不会等待承诺。为什么发电机的情况并非如此?redux-saga
,以及如何让我自己的发电机等待?
例如,这个传奇:
takeLatest('FETCH_USER_REQUESTED', function*() {
const fetchPromise = yield put(fetchUser());
const user = yield fetchPromise;
console.log(user)
yield 1
console.log(1)
})
将输出:
Promise
Object // <= user data fetched asynchronously
1
代替:
Promise
undefined
1
为什么 redux-saga 中的生成器不是这种情况,我该如何让我自己的生成器等待?
这是一个非常流行的信念,但是生成器本身与 Promise 或异步函数没有关系。生成器只是通过将一些资源和责任委托给上层函数来创建可中断的函数。
的情况下redux-saga
,有两部分:独立的saga runner进程和调度器(https://github.com/redux-saga/redux-saga/blob/master/src/internal/runSaga.js https://github.com/redux-saga/redux-saga/blob/master/src/internal/runSaga.js) ,由sagaMiddleware.run()
命令,以及effects
反应,将操作委托给主要的 saga 流程。
所以,ES6 中最简单的进程管理器,它模拟redux-saga
行为,将是这样的(非常简单):
const ProcessManager = (() => {
let context = new WeakMap();
function PM(rootSaga, lastValue) {
if(!context.has(rootSaga)) {
context.set(rootSaga, rootSaga())
}
const iterator = context.get(rootSaga);
const { done, value } = iterator.next(lastValue);
if(done) {
context.delete(rootSaga)
return;
}
if(Promise.resolve(value) === value) {
value.then((asyncValue) => PM(rootSaga, asyncValue))
} else {
PM(rootSaga, value)
}
}
return PM;
})()
const rootSaga = function* () {
yield new Promise(resolve => setTimeout(resolve, 500));
console.log('This will be printed after 500 ms from start');
yield new Promise(resolve => setTimeout(resolve, 500));
console.log('This will be printed after 1000 ms from start');
}
ProcessManager(rootSaga);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)