【问题标题】:then function getting executed before all the asynchronous calls are executed然后在执行所有异步调用之前执行函数
【发布时间】:2018-07-15 09:48:41
【问题描述】:

我正在调用后端服务以从 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
  }
}

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案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);
    

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

    另外,如果你能够并行做出承诺,你可以考虑使用Promise.all,以减少整个函数完成所需的时间。

    【讨论】:

    • 我已经添加了返回但仍然是相同的行为:(
    • @user1645290 如果您按照答案的规定正确链接所有承诺,您将无法获得相同的行为。 callback 在您的代码中看起来很可疑。使用 Promise 时不应该有随机回调,它们不是必需的。如果异步代码驻留在那里,它将无法按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 2019-02-06
    • 1970-01-01
    • 2021-03-24
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多