如何实现可取消的

如何实现可取消的

本文介绍了如何实现可取消的,有序的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我举了一个例子来展示我的目标:

I've put together an example to demonstrate what I'm getting at:

function onInput(ev) {
  let term = ev.target.value;
  console.log(`searching for "${term}"`);
  getSearchResults(term).then(results => {
    console.log(`results for "${term}"`,results);
  });
}

function getSearchResults(term) {
  return new Promise((resolve,reject) => {
    let timeout = getRandomIntInclusive(100,2000);
    setTimeout(() => {
       resolve([term.toLowerCase(), term.toUpperCase()]);
    }, timeout);

  });
}

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<input onInput="onInput(event)">

输入搜索框并观察控制台。搜索结果不按顺序返回!

Type in the "search" box and watch the console. The search results come back out of order!

当有新输入并保证结果按顺序返回时,我们如何取消任何待处理的承诺?

How can we cancel any pending promises when there's new input and guarantee the results come back in order?

推荐答案

您可以使用 Promise.race 取消上一个链的效果:

You can use Promise.race to cancel the effect of a previous chain:

let cancel = () => {};

function onInput(ev) {
  let term = ev.target.value;
  console.log(`searching for "${term}"`);
  cancel();
  let p = new Promise(resolve => cancel = resolve);
  Promise.race([p, getSearchResults(term)]).then(results => {
    if (results) {
      console.log(`results for "${term}"`,results);
    }
  });
}

function getSearchResults(term) {
  return new Promise(resolve => {
    let timeout = 100 + Math.floor(Math.random() * 1900);
    setTimeout(() => resolve([term.toLowerCase(), term.toUpperCase()]), timeout);
  });
}
<input onInput="onInput(event)">

这里我们通过注入 undefined 结果并对其进行测试来实现。

Here we're doing it by injecting an undefined result and testing for it.

这篇关于如何实现可取消的,有序的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:18