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

Using a function callback inside another function

我有我的 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)
      });
}

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

如果你想 运行 fetchBfetchA 完成后立即用 fetchA 的结果,你可以用结果调用 fetchBfetchA 个:

例子

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

  // ...
}

您可以使用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)
      });
}