【发布时间】:2021-05-31 14:55:37
【问题描述】:
在我的应用程序中, 有一个文本框,如果用户输入任何位置,则应用程序会搜索该位置并创建 5 个 fetch API 请求,间隔为 5 秒
if requestId :100 then requests will be ==>
1. API/GetResult?rv=0.5936085871062164 & jsonBodyHotel :100 //this is completed
2. API/GetResult?rv=0.5936085871062165 & jsonBodyHotel :100 //this is completed
3. API/GetResult?rv=0.5936085871062166 & jsonBodyHotel :100 //this is pending
4. API/GetResult?rv=0.5936085871062167 & jsonBodyHotel :100 //this is pending
5. API/GetResult?rv=0.5936085871062168 & jsonBodyHotel :100 //this is pending
Now before completeting those 5 request,if user enters new location ,then again application create 5 fetch API request
for new requestId :101
1. API/GetResult?rv=0.5936085871062174 & jsonBodyHotel :101
2. API/GetResult?rv=0.5936085871062175 & jsonBodyHotel :101
3. API/GetResult?rv=0.5936085871062176 & jsonBodyHotel :101
4. API/GetResult?rv=0.5936085871062177 & jsonBodyHotel :101
5. API/GetResult?rv=0.5936085871062178 & jsonBodyHotel :101
Once the above process starts ,we need to abort all API with old requestId,
here for an instance ,
3. API/GetResult?rv=0.5936085871062166 & jsonBodyHotel :100 //this needs to be aborted
4. API/GetResult?rv=0.5936085871062167 & jsonBodyHotel :100 //this needs to be aborted
5. API/GetResult?rv=0.5936085871062168 & jsonBodyHotel :100 //this needs to be aborted
and so on for every new request .......
我创建的内容如下,我在控制台中没有收到任何错误,但也无法中止旧请求
import AbortController from "abort-controller"
class ClassContainer extends React.Component {
constructor(props) {
super(props);
this.controller = new AbortController();
this.signal = this.controller.signal;
}
// Below is the function gets executed whenevr user enter any new location , show loading indictaor and creates 5 fetch API request
searchTravel=()=>{
this.controller.abort();
//show loader
//API hit to get new requestId
this.getData(requestId)
}
// This is a function which will create 5 fetch API request for every requestId==>
getData=(requestId)=>{
jsonBodyHotel : will have requestId & other stuff
const response = fetch("/API/GetResult" + "?rv=" + Math.random(), {
method: "POST",
body: jsonBodyHotel,
headers: {
"Content-type": "application/json; charset=UTF-8",
},
},this.signal)
}
如何在每次生成新请求时中止旧请求
【问题讨论】: