然后在执行所有异步调用之前执行函数

IT技术 javascript reactjs redux
2021-05-19 07:41:40

我正在调用后端服务以从该loadContent方法的第一次获取中获取所有可用的 IDS,并且我正在从后端获取所有 IDS。

从初始服务中随机选择 10 个 IDS,我单独调用另一个服务来获取 ID 的完整数据。我也能够获取所有数据,但在获取所有数据之前,会调用带有调度的函数,因为数据未在存储中设置。

export function loadContent(requestUrl) {
  return dispatch => {

   return fetch( /* initial calls to get all the ids */ ).then((response) => {
      return response.json();
    }).then((data) => {
      console.log(data);
      var stories = [];


      var x = 0;
      var loopArray = function(data) {
      return customAlert(data, function() {


        });
      }

      function customAlert(topStories, callback) {
        var randomNumber = topStories[Math.floor(Math.random() * topStories.length)];
        fetch( /* call service with individual id */ ).then((response) => {
          return response.json();
        }).then((output) => {
          console.log(output);
          stories[x] = output;
          x++;

          // any more items in array? continue loop
          if (x <= 10) {
            loopArray(data);
          } else {
            return stories;
          }
        })
      }
     return loopArray(data);
    }).then((stories) => {
      dispatch({
        type: "LOAD",
        payload: stories
      });
    }).catch((err) => {
      console.log("There has been error");
    })


  };
}

export function load(news) {
  return {
    type: 'LOAD',
    news: news
  }
}
1个回答

您需要从其内部块中获取return每一个Promise,以便您可以将它们全部链接在一起,并且.then((stories)仅在它们全部完成后才执行。即,更改为:

return fetch( /* initial calls to

// ...

return customAlert(data, function() {

// ...

return fetch('to get the...

// ...

if (x <= 10) {
  return loopArray(data);
}

所以最初的调用

return loopArray(data);

只有在所有其他 Promise(现在与初始调用正确链接)解决后,才会最终解决。

您还可以使用 来简化代码push,例如:

stories.push(output);

而不是保留数组x当前长度变量,stories以便您可以分配给stories[x].

此外,Promise.all如果您能够并行做出Promise,您可以考虑使用,以减少完成整个功能所需的时间。