如何检查 Api 是否被触发以及如何在触发时中止 API

问题描述

我正在创建一个搜索页面,以搜索有关 keyup 的一些数据,为每个 keyup 调用一个 API,但如果调用第二个 API,我想停止前一个调用

myFunction(term) {
    const controller = new AbortController();
    const signal = controller.signal;
    controller.abort();
    var apiUrl = window.BASE_URL + '/search?param=' + term;
    console.log(apiUrl);
    this.setState({
      searching: true
    });
    return fetch(apiUrl,{ credentials: 'include',signal: signal })
      .then(this.handleErrors)
      .then(response => response.json())
      .then(responseJson => {
         console.log(responseJson);
      })
      .catch(error => {
        console.error(error);
      });
  }

解决方法

您已经为 signal 调用提供了 fetch,但是由于您在函数范围内对其进行了初始化,因此外部世界没有引用它,因此无法使用它。

>

所以f.ex。将其作为参数传递给您的函数:

const controller = new AbortController();
const signal = controller.signal;

myFunction(term,signal) { ... }

然后在需要时调用中止:

signal.abort()

还要确保您没有使用 IE,因为它是 not supported on that browser.


将信号对象存储在外部并在调用 myFunction 时重新初始化它的其他选项:

signal;

myFunction(term) {
  this.signal ? signal.abort() : false;

  const controller = new AbortController();
  this.signal = controller.signal;

  < ... >
}
,

取消先前获取请求的示例:

const controller = useRef<AbortController>() // useRef: for function component. 
// You can create a property in a class component to store this 
// (e.g. `this.controller = null` in your constructor)  

function fetchAndAbortPrevious() {
  controller.current?.abort()
  controller.current = new AbortController()
  fetch('https://cat-fact.herokuapp.com/facts',{
    signal: controller.current.signal,})
    .then((response) => response.json())
    .then((response) => console.log(response))
    .catch((err) => console.log('error: ',err))
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...