首页 > 解决方案 > 添加加载指示器以选择菜单

问题描述

如果我删除.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();
});

标签: javascript

解决方案


更改.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))

推荐阅读