如果第一个提取调用未返回任何数据,如何添加条件来调用第二个提取?

时间:2019-06-21 20:56:53

标签: javascript reactjs

我需要拨打2个电话。第一个访存调用将检查本地数据库中的数据。如果数据在那里,则更新状态。如果数据不存在,则需要进行第二次提取调用,该调用将转到外部api以检索信息。如果找到数据,请更新状态。

如果在两个提取调用中均未找到数据,则需要向用户显示以下信息:“未找到记录。请手动添加记录。”

到目前为止,这是我在组件中拥有的:

this.state = {
  data: []
};

search = e => {
  e.preventDefault();

  fetch(`url1`, {
    method: "GET",
    headers: {
      "content-type": "application/json"
    }
  })
    .then(response => response.json())
    .then(response => {
      this.setState({
        data: response
      });
    })
    .catch(error => {
      console.log(error);
    });

  fetch(`url2`, {
    method: "GET",
    headers: {
      "content-type": "application/json"
    }
  })
    .then(response => response.json())
    .then(response => {
      this.setState({
        data: response
      });
    })
    .catch(error => {
      console.log(error);
    });
};

render() {
  return(
    <button name="record" onClick={this.search}>Search Record</button>
  )
}

2 个答案:

答案 0 :(得分:0)

为后备提取创建一个函数,然后在未接收到任何数据时在第一次提取中调用它。

this.state = {
  data: []
};

search = e => {
  e.preventDefault();

  const fetch2 = () => {
    fetch(`url2`, {
        method: "GET",
        headers: {
          "content-type": "application/json"
        }
      })
      .then(response => response.json())
      .then(response => {
        this.setState({
          data: response
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  fetch(`url1`, {
      method: "GET",
      headers: {
        "content-type": "application/json"
      }
    })
    .then(response => response.json())
    .then(response => {
      if (response) { // however you need to check for valid response
        this.setState({
          data: response
        });
      } else {
        fetch2();
      }

    })
    .catch(error => {
      console.log(error);
    });


};

render() {
  return ( <
    button name = "record"
    onClick = {
      this.search
    } > Search Record < /button>
  )
}

答案 1 :(得分:0)

您应该在设置状态之前检查异步调用链中的响应,如果响应长度为零,则触发另一个访存(或任何promise)。非常方便的是,触发提取将被链接到您为第一个承诺指定的其余回叫。

search = e => {
  e.preventDefault();
  const options = {
    method: "GET",
    headers: {
      "content-type": "application/json"
    }
  }

  fetch(`url1`, options)
  .then(response => response.json())
  .then(response => response.length > 0 
                    ? response 
                    : fetch(`url2`, options).then(response => response.json()))
  .then(response => this.setState({ data: response }))
  .catch(error => console.log(error));
};