javascript - 添加加载指示器以选择菜单
问题描述
如果我删除.then(anotherDropdown.remove(0))
,我会看到“正在加载...”作为预期的第一个选项,但如果我把上面的代码行放回去,我永远看不到它。fetch 调用完成后,如何查看并删除它?
dropdown.addEventListener('change', function () {
var id = this.value;
// set the first option to Loading... when option selected by user
var option = document.createElement("option");
option.text = "Loading...";
anotherDropdown.add(option, dropdown[0]);
function getData() {
fetch(url + id, {
method: 'POST',
body: JSON.stringify(apiData),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(resp => resp.json())
.then(resp => console.log(resp))
// this line removes the loading message instantly and it is never seen
.then(anotherDropdown.remove(0))
}
getData();
});
解决方案
更改.then(anotherDropdown.remove(0))
为.then(()=>anotherDropdown.remove(0))
.then
接受回调函数作为参数。
最好使用.finally
而不是.then
这种情况。
所以
fetch(url + id, {
method: 'POST',
body: JSON.stringify(apiData),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(resp => resp.json())
.then(resp => console.log(resp))
.finally(() => anotherDropdown.remove(0))
推荐阅读
- javascript - 追加新元素后,jQuery UI 可排序刷新不起作用
- javascript - 最大调用不超过 NodeJS 中某些函数内部的代码
- matlab - 使用 simout 收集数据以进行数千次运行的实验
- asp.net-mvc - 如何查看模态框内的编辑视图
- ruby-on-rails - 尽管在 gemfile/rails 帮助器中定义了 rspec/rails,但 Rspec 产生了一个未定义的方法 `route_to'
- c++ - 从 C++ 中的后缀表达式字符串打印单个操作
- python - 使用键作为元组的字典的有效循环
- python-3.x - 如何解决 pygame 中不透明度更改的 OOP 问题
- powershell - Powershell Get-Content 虚假失败
- matlab - Matlab使用矢量化的多个线性最小二乘