【问题标题】:make promise.all wait until both API's are done before it completes让 promise.all 等到两个 API 都完成后再完成
【发布时间】:2019-03-08 22:01:08
【问题描述】:

我的个人资料正在这样做..

Promise.all([this.fetchInsights(), this.fetchTouchpoints()])
     .then(([insights, touchpoints]) =>
       console.log(insights, touchpoints)
     )

这里是fetchInsights()

fetchInsights = () => {
  fetch('API_URL' + this.queryParams.custId + '/' + this.queryParams.acctNo, {
    method: 'GET', // or 'PUT'
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(res => res.json())
  .catch(error => console.error('Error:', error));
};

这里是fetchTouchpoints()

  fetchTouchpoints = () => {
    fetch('API_URL' + this.queryParams.custId + '/' + this.queryParams.acctNo, {
      method: 'GET', // or 'PUT'
      headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    }).then(res2 => res2.json())
    .catch(error => console.error('Error:', error));
  };

当我运行它时,页面立即读取未定义,未定义。这是因为 API 调用尚未完成,因此见解和接触点均未定义。

当我在 Eclipse(这是一个 Springboot 应用程序)中查看日志时,我看到响应都是成功的,并且它会在控制台中打印出响应......但应用程序没有更新。

如何让 Promise.all 在两个 API 调用完成后打印日志?

我尝试将Promise.all 放入componentDidMountrender()

任何帮助将不胜感激!

【问题讨论】:

  • 你的 fetchX 函数没有 return 他们正在创建的承诺,所以 Promise.all 什么都不等。

标签: reactjs promise


【解决方案1】:

你忘了返回承诺。

顺便说一句,为了代码的可读性,请使用template strings

这里是固定的fetchInsights

fetchInsights = () => {
  return fetch(`API_URL${this.queryParams.custId}/${this.queryParams.acctNo}`, {
    method: 'GET', // or 'PUT'
    headers:{
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(res => res.json())
  .catch(error => console.error('Error:', error));
};

【讨论】:

  • 在 Promise.all 中分离响应的最佳方法是什么?在 then([1, 1]) 之外,我该如何做第一个响应,然后是第二个响应?
  • 如果您依赖第一个的响应,您可以在第一个的.then 中调用第二个。或者你编写一个异步函数并使用await fetch...
猜你喜欢
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 2014-12-17
  • 2018-12-28
  • 1970-01-01
  • 2011-07-04
相关资源
最近更新 更多