请求时序问题 - 图1

解决方案:

1.请求1还没有结果返回时,不允许发起请求2,通过loading或控制触发按钮,事件形式实现;
2.取消慢接口的请求。

正确的打开方式:

通过取消慢接口请求,可解决异步请求时序问题引起的搜索关键词跟结果存在不一致的问题:

1.fetch方式:

使用 fetch 发起一个 post 请求:

  1. fetch('http://localhost:3000/getList', {
  2. method: 'POST',
  3.   headers: {
  4.     'Content-Type': 'application/json;charset=utf-8'
  5.   },
  6.   body: JSON.stringify({
  7. id: 1
  8.   })
  9. }).then(result => {
  10. console.log('result', result);
  11. });

可以使用AbortController来实现请求取消:

  1. this.controller?.abort(); // 重新发起 http 请求之前,取消上一次请求
  2. const controller = new AbortController(); // 创建 AbortController 实例
  3. const signal = controller.signal;
  4. this.controller = controller;
  5. fetch('http://localhost:3000/getList', {
  6. method: 'POST',
  7.   headers: {
  8.     'Content-Type': 'application/json;charset=utf-8'
  9.   },
  10.   body: JSON.stringify({
  11. id: 1
  12.   }),
  13. signal, // 信号参数,用来控制 http 请求的执行
  14. }).then(result => {
  15. console.log('result', result);
  16. });

2.axios方式:

发起 post 请求:

  1. axios.post('http://localhost:3000/getList', {
  2. headers: {
  3. 'Content-Type': 'application/json;charset=utf-8'
  4. },
  5. data: {
  6. id: 1,
  7. },
  8. })
  9. .then(result => {
  10. console.log('result:', result);
  11. });

axios 发起的请求可以通过 cancelToken 来取消。

  1. this.source?.cancel('The request is canceled!');
  2. this.source = axios.CancelToken.source(); // 初始化 source 对象
  3. axios.post('http://localhost:3000/getList', {
  4. headers: {
  5. 'Content-Type': 'application/json;charset=utf-8'
  6. },
  7. data: {
  8. id: 1,
  9. },
  10. }, { // 注意是第三个参数
  11. cancelToken: this.source.token, // 这里声明的 cancelToken 其实相当于是一个标记或者信号
  12. })
  13. .then(result => {
  14. console.log('result:', result);
  15. });

3.XMLHttpRequest方式:

发起请求:

  1. var xhr1 = new XMLHttpRequest();
  2. xhr1.open('get', 'https://developer.mozilla.org', true);
  3. xhr1.send();
  4. xhr1.onreadystatechange= function () {
  5. console.log(xhr.responseText, '-- respone');
  6. }

XMLHttpRequest调用对应的xhrInstance.abort() 会终止当前的请求:

  1. xhr1.abort();
  2. var xhr2 = new XMLHttpRequest();
  3. xhr2.open('get', 'https://developer.mozilla.org', true);
  4. xhr2.send();
  5. xhr2.onreadystatechange= function (){
  6. console.log(xhr.responseText, '-- respone');
  7. }