简体   繁体   English

Redux Saga-在异步回调中调用“收益放置”

[英]Redux Saga - call “yield put” inside async callback

Inside my saga, I am calling an async function and passing it a callback. 在我的传奇中,我正在调用异步函数并将其传递给回调函数。 The reason I am passing it a callback is because it can be called a few times from the async function. 我将其传递给回调函数的原因是因为它可以从async函数中调用几次。

How can I call "yield put" from inside the callback which should be called more than one time from inside the async function. 我如何从回调内部调用“ yield put”,应该从async函数内部多次调用。

As you have noticed, there is no way to yield inside a nested function of your generator function. 您已经注意到,无法在生成器函数的嵌套函数内部yield Instead you can convert the callback style async function into a promise, and use the call effect . 相反,您可以将回调样式异步函数转换为Promise,并使用call effect

function* generator() {
  const results = yield call(function() {
    return new Promise(function(resolve, reject) {
      const results = [];
      asyncFunction(function(result) {
        if (async function is done) { resolve(results) }
        else { results.push(result) }
      });
    });
  });
  yield put(action(results));
}

This is a common pattern, but the tricky part for you will be knowing when asyncFunction has completed. 这是一种常见的模式,但是对您来说棘手的部分是知道asyncFunction完成的时间。 It will need some way to signal that it has called the callback function for the last time. 它需要某种方式来表明它已最后一次调用回调函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM