我正在开发一个搜索栏,当用户开始输入时它会调用 API。每次击键,都会向服务器发出请求并返回响应。
我想在对服务器进行新调用之前拒绝先前的 promise ,我该如何实现?现在我遇到了旧 promise 返回并更改 UI 的问题,这导致它闪烁。
export const makeGetPlaceData = (axios, uri) => (name, country) => {
const promise = new Promise((resolve, reject) => {
axios.get(`${uri}?name=${name}&country=${country}`)
.then(response => {
setTimeout(() => resolve(response), 2000);
})
.catch(error => {
console.log('rejected', error);
reject(error);
});
});
return promise;
};
使用setTimeout
来模拟缓慢的网络响应。
最佳答案
我通常在处理程序级别而不是 promise 级别执行此操作。其要点是您可以跟踪已调用的电话数量,并且每个回调都知道其电话号码。当 promise 解决时,如果回调不再是最新的,则提前返回。
let lastCallId = 1;
function doCall() {
var myCallId = lastCallId;
lastCallId++;
api.doSomething().then((data) => {
if (myCallId !== lastCallId) return;
// Do something with the data
});
}
关于javascript - 在创建新 Promise 之前拒绝 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302676/