在react-native中处理多个api调用

时间:2021-07-13 03:03:25

I am trying to implement a search field what happens here is whenever user enters text i text field the timer is reset to 300 ms and then an api call(search) is sent to fetch autocomplete results now after receiving those results the app waits for another 1s and sends another request. during this duration the user may enter some more text. So one scenario which I am assuming is that the search api is called and before the response arrives user changes the text sending another pre search call now the response for search arrives and is mistaken for pre search response and hence gives the error. Is there any workaround to this?

我正在尝试实现一个搜索字段,这里发生的是每当用户输入文本i文本字段时,计时器重置为300毫秒,然后发送api调用(搜索)以获取自动完成结果现在收到这些结果后,应用程序等待另一个1s并发送另一个请求。在此期间,用户可以输入更多文本。因此,我假设的一个场景是调用搜索API,并且在响应到达之前,用户更改发送另一个预搜索调用的文本,现在搜索的响应到达并且被误认为是预搜索响应,因此给出了错误。这有什么解决方法吗?

1 个解决方案

#1


0  

What you want is to cancel the in-flight request when the users enters more text.

您想要的是在用户输入更多文本时取消正在进行的请求。

I'm assuming you're using the fetch api. Unfortunately it doesn't have a way to cancel the request as per the Promise spec. You can use XMLHttpRequest directly if you need to cancel the request.

我假设你正在使用fetch api。不幸的是,根据Promise规范,它没有办法取消请求。如果需要取消请求,可以直接使用XMLHttpRequest。

Another possibility is to check in the fetch response handler if the initial text being searched has changed. In that case you don't do any action in that handler.

另一种可能性是检查获取响应处理程序,如果搜索的初始文本已更改。在这种情况下,您不会在该处理程序中执行任何操作。

#1


0  

What you want is to cancel the in-flight request when the users enters more text.

您想要的是在用户输入更多文本时取消正在进行的请求。

I'm assuming you're using the fetch api. Unfortunately it doesn't have a way to cancel the request as per the Promise spec. You can use XMLHttpRequest directly if you need to cancel the request.

我假设你正在使用fetch api。不幸的是,根据Promise规范,它没有办法取消请求。如果需要取消请求,可以直接使用XMLHttpRequest。

Another possibility is to check in the fetch response handler if the initial text being searched has changed. In that case you don't do any action in that handler.

另一种可能性是检查获取响应处理程序,如果搜索的初始文本已更改。在这种情况下,您不会在该处理程序中执行任何操作。