【问题标题】:Resolve promise(s) inside map of redux saga generator在 redux saga 生成器的 map 中解析 promise(s)
【发布时间】:2020-08-20 11:47:50
【问题描述】:

我有一个生成器,用于更新对象。在这里,我需要调用多个返回承诺的函数,所以我使用 yield all 并且(明确的双关语)一切都很好。像这样的:

function* updateTheThing() {
  ...
  const [resultA, resultB, resultC] = yield all([funcA(), funcB(), funcC()]);
  ...
}

这适用于更新单个项目,但我想更新一组项目。我的想法是在项目上使用地图和地图,但问题是我无法在地图内屈服。我之前做过类似的事情,我需要做的只是调用一些这样的 API:

const promises = things.map(thing => { 
  return call(api.someEndpoint);
});

const data = yield all(promises);

但我不能在这里这样做,因为我没有使用 redux saga 的调用。我现在的代码是这样的,但它不起作用:

function* updateAllTheThings() {
  try {
    const updatedThings = things.map(thing => {
      const resultA = funcA();  // resultA is a promise
      const resultB = funcB();  // resultB is a promise
      const resultC = funcC();  // resutlC is a promise
    });
  } catch (error) {
    console.log(`error updating all the things: ${error}`);
  }
}

resultA、resultB 和 resultC 是承诺,但我需要解析的值,因为我需要在 map 语句中进一步使用它。

也许我的方法是错误的,但我很难过。有人有什么建议吗?

【问题讨论】:

    标签: reactjs react-redux es6-promise redux-saga


    【解决方案1】:

    好的,在 Nicolas Tower 在this question 的回答的帮助下,我能够重新思考并重新编写我的代码以按预期工作。我会在此处添加我的解决方案,以防有人发现它有帮助。

    所以我决定使用的部分问题是,用他们的话说,创建一个迷你传奇,所以我的代码现在是这样的:

    function* updateAllTheThings() {
      try {
        const promisedThings = things.map(thing => {
          return call (function* () {
            const resultA = funcA();  // resultA is a promise
            const resultB = funcB();  // resultB is a promise
            const resultC = funcC();  // resutlC is a promise
          });
        });
        const updatedThings = yield all(promisedThings);
        ... 
      } catch (error) {
        console.log(`error updating all the things: ${error}`);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多