在同一函数中进行两次调用

时间:2019-01-21 17:07:17

标签: javascript api react-native fetch

我有两个请求GET和POST请求,我正在获取GET请求并在和array内设置响应状态,我想将此数组传递给POST请求主体,然后获取POST请求所以我可以打电话,问题是它没有在GET呼叫中设置状态,并且总是返回undefined,我不知道为什么,这里是代码:

我的构造函数:

constructor(props){
  super(props);
  this.state = {
    info: [],
  }
}

功能

myFunction = async () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response });
      fetch("https://myapp.com/submit_info", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: this.state.info.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};

1 个答案:

答案 0 :(得分:2)

您忘记了返回承诺,然后使用response对象来设置infoID字段,而不是状态导致对this.setState的调用是异步的,并且当您进行第二次api调用。

myFunction = () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response }); // async call
      return fetch("https://myapp.com/submit_info", {
        // return promise for chaining
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: response.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};