然后在执行所有异步调用之前执行函数 [英] then function getting executed before all the asynchronous calls are executed

查看:102
本文介绍了然后在执行所有异步调用之前执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling a backend service to fetch all the IDS available in the first fetch from the loadContent method and I am getting all the IDS from backend.

随着初始服务中随机选择的10个IDS,我正在单独调用另一个服务来获取ID的完整数据。我也能够获取所有数据,但在获取所有数据之前,调用函数被称为,因为数据未在商店中设置。

With the randomly picked 10 IDS from the initial service, I am calling another service individualy to fetch the complete data of the ID. I am also able to get all the data, but before getting all the data the function with dispatch is getting called due to which the data is not getting set in the store.

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
  }
}


推荐答案

你需要从内部块返回每个 Promise ,这样你就可以将它们全部链接起来并拥有 .then((故事) )只有在完成后才执行。即,改为:

You need to return each Promise from its inner block so that you can chain them all together and have the .then((stories) execute only once they're all complete. Namely, change to:

return fetch( /* initial calls to

// ...

return customAlert(data, function() {

// ...

return fetch('to get the...

// ...

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

以便初次调用

return loopArray(data);

只会在每个其他Promise(现在已经与初始调用正确链接)解决后才会最终解决。

will only finally resolve once every other Promise (now properly chained with the initial call) has resolved.

您也可以通过以下方式简化代码:使用 push ,例如:

You also might simplify your code by using push, for example:

stories.push(output);

而不是保留 x 的变量故事数组的当前长度,以便您可以分配到故事[x]

rather than keep an x variable of the current length of the stories array so you can assign to stories[x].

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

Also, you may consider using Promise.all if you're able to make promises in parallel, so as to reduce the time necessary for the whole function to complete.

这篇关于然后在执行所有异步调用之前执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆