我正在创建一个搜索页面,用于搜索 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);
});
}
最佳答案
取消先前获取请求的示例:
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))
}
关于javascript - 如何检查 Api 是否被触发以及如何中止 api 如果触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66166872/