Investigating Real‑Time Search Result Errors

Why type‑ahead shows stale results and how to fix it: cancel pending requests and show loading states.

Feb 9, 2020 · 2 min read · 698 Words · -Views -Comments · Digital Life
🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Problem

用一个例子来描述吧,当用户输入关键词A,触发了检索,一秒钟后,用户输入了关键词 B,触发了检索,这时A检索结果回来了,呈现出来了列表展示,用户诧异,为何输入的B,返回了A结果,再过一会儿B结果回来。用户在可视化的情况下,看到了错误的结果,紧接着看到了正确的结果。

Analysis

接口慢是个问题,但是除了接口慢,也可以看到整个的实时检索存在设计缺陷。

  1. 当触发了第二次请求时,第一次请求如果还在请求中应该中断,这样对于开销来说小一些
  2. 用户之所以会误认为A结果集是用户输入B的结果,还有一个问题是,是否当执行B检索时,就不应该呈现结果集,通过loading等形式呈现给用户还正在检索

百度比如输入关键词时,推荐列表并没有loading动画,我想根本原因是因为足够的快,所以不需要有loading

Impact of canceling on the backend

如上,当我们取消了一个已经发出的请求,但是因为请求本身是个异步的过程,所以后端还是会把这个请求处理流程走完。所以严格来说,我们取消了请求,对于前端的开销有所减小,但是对于后端无任何影响。

Solutions

  1. 执行新的请求时,如果老的请求还在进行,进行取消

    前端的请求类库,我使用的axios,而本身类库提供了cancel的方案,所以在全局拦截器里进行下配置即可。具体代码可参考这里

  2. 执行请求时,增加loading显示,让用户意识到当前的结果集是历史的,最新的正在检索中

Final Thoughts

经过以上的方案处理,总结下。

  1. 不会呈现错误的结果给用户
  2. 支持了取消pending请求,节约了一定的前端性能开销
  3. 除了上述的两点,也可以对于检索增加防抖处理,比如延迟1秒执行检索,确保高频输入不触发额外的检索。

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover