在另一个函数中使用函数回调

时间:2018-07-26 17:32:28

标签: javascript reactjs fetch-api

我的react元素内部有几个函数。我想将另一个函数内部的一个函数的回调用作变量。这两个函数都使用Fetch API。

fetchA = () => {
    var data = new FormData();
    data.append('file', this.state.selectedFile, this.state.selcetedFile.name);
    fetch('/files', {method: 'POST', body: data})
      .then(response => {
        return response.json()})
      .then(function(json) {
        console.log(json));})
      .catch(function(error) {
         console.log(error)
      });
}

fetchB = () => {
    fetch('/trust', {method: 'put', body: **HERE**})
      .then(response => {
        console.log('SUCCESS')})
      .catch(function(error) {
         console.log(error)
      });
}

您可以在第二个访存调用的主体中看到我想引用在我的第一个函数的响应中生成的json的位置。有人可以为此推荐一个简单的解决方案吗?

2 个答案:

答案 0 :(得分:2)

如果要在fetchB完成后立即使用fetchA的结果来运行fetchA,则只需调用fetchB的结果来调用fetchA

示例

class App extends React.Component {
  fetchA = () => {
    const { selectedFile } = this.state;
    const data = new FormData();

    data.append("file", selectedFile, selectedFile.name);

    fetch("/files", { method: "POST", body: data })
      .then(response => {
        return response.json();
      })
      .then(result => {
        this.fetchB(result);
      })
      .catch(error => {
        console.log(error);
      });
  };

  fetchB = data => {
    fetch("/trust", { method: "put", body: data })
      .then(response => {
        console.log("SUCCESS");
      })
      .catch(error => {
        console.log(error);
      });
  };

  // ...
}

答案 1 :(得分:0)

您可以使用async/await使其像同步操作一样look

fetchA = async () => {
    var data = new FormData();
    data.append('file', this.state.selectedFile, this.state.selcetedFile.name);
    const response = await fetch('/files', {method: 'POST', body: data});
    return await response.json();
}

fetchB = async () => {
    const body = await fetchA();
    fetch('/trust', {method: 'put', body})
      .then(response => {
        console.log('SUCCESS')})
      .catch(function(error) {
         console.log(error)
      });
}