我有一个正在发送 http 请求的应用程序,每次用户键入时都会返回一个 promise 。我让它每 500 毫秒去抖一次。有时我请求的 api 需要很长时间才能响应。例如,我对 a
发出搜索请求,该请求需要很长时间才能响应,但随后用户继续键入以完成 a+x
的查询,该查询几乎立即解析,但a+x
的结果被 a
的先前请求覆盖。
TL;DR:如果在当前解析之前调用新的 Promise,如何取消当前的
最佳答案
创建一个变量来计算您的请求:
var effectiveRequestNumber = 0;
function asyncRequest() {
var requestNumber = ++effectiveRequestNumber; // storing our request number
doSomething().then(function(response) {
// if the function was invoked after this request, then these two won't match
if (effectiveRequestNumber !== requestNumber) {
return;
}
applyResponse(response); // we are fine - applying the response
});
}
关于javascript - promise 排队?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898985/