只让最后一个API调用通过 [英] let only last API call get through

查看:41
本文介绍了只让最后一个API调用通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个输入字段,当您在其中输入内容时,它将对我们的后端进行API调用,我遇到的问题是:

So, I have this inputfield, when you type something in it, it makes an API call to our backend, the problem I have is:

假设我们正在输入测试,我将打出4个电话:

Let's say we are typing test, I will make 4 calls out of this:

  • t
  • te
  • tes
  • 测试

因为调用"t"所需的时间比测试"所需的时间长得多,所以最后将加载来自"t"的数据.这意味着我没有从测试"中获取所需的数据.

because the call for 't' takes much longer than 'test', the data from 't' will be loaded in at the end. which means I don't get the requested data from 'test'.

我的问题是,有什么办法可以取消上一个请求?('t','te','tes'),只让您的上一个电话打通?还是只是优化API速度的性能?

My question is, is there any way you can cancel the previous request? ('t', 'te', 'tes') and only let your last call get through? Or is this just optimizing performance of the API speed?

我已经尝试了半秒的超时,但是有时问题仍然存在.

I've already tried with a timeout of half a second but the problem still remains sometimes.

推荐答案

当您对用户输入进行异步调用时,异步结果解析的顺序可能不是用户输入的顺序(因此不会出现反跳问题).当用户键入 s 时,您使用 s 进行异步调用,然后用户键入 e ,并使用 se进行异步调用.现在有2个未解决的异步调用,一个带有 s ,一个带有 se .

When you make an async call on user input then the order the async results resolve may not be the order the user gave the inputs (so not a debounce issue). When user types s then you make an async call with s, then the user types e and you make an async call with se. There are now 2 async calls unresolved, one with s and one with se.

s 调用需要一秒钟,而 se 调用需要10毫秒,然后 se 首先解析,并将UI设置为 se ,但此后解析 s 并将UI设置为 s 的结果.您现在的UI不一致.

Say the s call takes a second and the se call takes 10 milliseconds then se resolves first and UI is set to result of se but after that s resolves and the UI is set to result of s. You now have an inconsistent UI.

解决此问题的一种方法是使用反跳,并希望您永远不会收到持续时间超过反跳时间的异步调用,但无法保证.另一种方法是取消较旧的请求,但这很难实施,并且并非所有浏览器都支持.我在下面显示的方式只是在提出新请求时拒绝异步诺言.因此,当用户键入 s e 请求时,会发出 s se 的请求,而当 s se 之后解析,它将被拒绝,因为它已被更新的请求替换.

One way to solve this is with debounce and hope you'll never get async calls that last longer than the debounce time but there is no guarantee. Another way is cancel older requests but that is too much of a pain to implement and not supported by all browsers. The way I show below is just to reject the async promise when a newer request was made. So when user types s and e requests s and se are made but when s resolves after se it will be rejected because it was replaced with a newer request.

const REPLACED = 'REPLACED';
const last = (fn) => {
  const current = { value: {} };
  return (...args) => {
    const now = {};
    current.value = now;
    return Promise.resolve(args)
      .then((args) => fn(...args))
      .then((resolve) =>
        current.value === now
          ? resolve
          : Promise.reject(REPLACED)
      );
  };
};
const later = (value, time) =>
  new Promise((resolve) =>
    setTimeout(() => resolve(value), time)
  );
const apiCall = (value) =>
  //slower when value length is 1
  value.length === 1
    ? later(value, 1000) //takes a second
    : later(value, 100); //takes 100ms
const working = last(apiCall);
const Api = ({ api, title }) => {
  const [value, setValue] = React.useState('');
  const [apiResult, setApiResult] = React.useState('');
  React.useEffect(() => {
    api(value).then((resolve) => {
      console.log(title, 'resolved with', resolve);
      setApiResult(resolve);
    });
  }, [api, title, value]);
  return (
    <div>
      <h1>{title}</h1>
      <h3>api result: {apiResult}</h3>
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
};
const App = () => (
  <div>
    <Api
      api={apiCall}
      title="Broken (type 2 characters fast)"
    />
    <Api api={working} title="Working" />
  </div>
);
ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

这篇关于只让最后一个API调用通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆