用 window.stop 停止 Promise [重复]
Posted
技术标签:
【中文标题】用 window.stop 停止 Promise [重复]【英文标题】:Stopping a Promise with window.stop [duplicate] 【发布时间】:2020-12-10 05:04:24 【问题描述】:我正在使用 fetch
获取 json 数据并使用结果呈现列表项。包含fetch
的函数由按钮触发。但是,如果我在初始 fetch
仍在运行时单击它,来自它的数据将在我的新呼叫之上加载。
我已使用window.stop()
来阻止此行为,但有更好的解决方案吗?
function updateTable()
fetch('/json')
.then((response) => return response.json())
.then((response) =>
response.records.forEach(el =>
return '<li>' + el.Name + '</li>';
)
)
$('button').click(function()
window.stop();
$('body').empty();
updateTable()
)
已编辑答案:在重新阅读链接线程时,使用fetch
使用新的signal
属性,我更新了我的代码以使用新的AbortController
。记录here 的诀窍是在再次调用该函数时重新定义控制器。与window.stop()
相比的优势在于,停止只会影响fetch
。
var controller = "";
var signal = "";
function updateTable()
controller = new AbortController();
signal = controller.signal;
fetch('/json', signal)
.then((response) => return response.json())
.then((response) =>
response.records.forEach(el =>
return '<li>' + el.Name + '</li>';
)
)
$('button').click(function()
controller.abort();
$('body').empty();
updateTable()
)
【问题讨论】:
在加载时禁用该按钮,或在您单击该按钮时取消挂起的 Web 请求。 不应将答案编辑到问题中。相反,将正确答案标记为“已接受”。如果您自己找到解决方案,请写下您自己的答案,并将其标记为已接受。 抱歉,我无法添加新答案(问题已被阻止)。为什么还要做这一切?我相信它会帮助其他人。 【参考方案1】:这可以通过一个简单的变量来完成。这用于确定 fetch 是否仍在处理中。
var allRecords = [];
var processing = false;
function updateTable()
fetch('/json' )
.then((response) => return response.json())
.then((response) =>
processing = false;
response.records.forEach(el =>
return '<li>' + el.Name + '</li>';
)
)
$('button').click(function()
if(processing === false)
processing = true;
$('body').empty()
updateTable()
)
【讨论】:
谢谢。但是,对于大量的记录,这仍然意味着forEach
不会立即停止。以上是关于用 window.stop 停止 Promise [重复]的主要内容,如果未能解决你的问题,请参考以下文章
停止 angular-ui-router 导航,直到 promise 解决
Bluebird Promise.all - 多个 Promise 完成聚合成功和拒绝