gpt4 book ai didi

javascript - promise 排队?

转载 作者:行者123 更新时间:2023-11-28 18:31:33 27 4
gpt4 key购买 nike

我有一个正在发送 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com