程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在 JS 中使用 fetch 的问题大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在 JS 中使用 fetch 的问题?

开发过程中遇到在 JS 中使用 fetch 的问题的问题如何解决?下面主要结合日常开发的经验,给出你关于在 JS 中使用 fetch 的问题的解决方法建议,希望对你解决在 JS 中使用 fetch 的问题有所启发或帮助;

代码如下:

        but.addEventListener("click",() => {
        fetch("employees.Json")
            .then(resp => {

                if (res.status >= 400) {
                    return Promise.reject();
                }
                console.log(resp);

                return resp.Json();
                // const a = resp.Json();
                // for (const worker of a) {
                //         const employee = AddDOMWorker(worker);
                //         res.appendChild(employee);
                //     }

            })
            .then(
                (emps) => {
                    for (const worker of emps) {
                        const employee = AddDOMWorker(worker);
                        res.appendChild(employee);
                    }
                }
            )
    });

    function AddDOMWorker(employee) {
        const div = document.createElement("div");
        div.classList.add("frIEnd");
        div.textContent = `${employee.ID} ${employee.position}`;
        return div;
    }

为什么我应该在返回 resp.Json() 后使用 .then。为什么我不能把 resp.Json() 放在 a 变量中并去掉第二个 .then (注释代码)?

解决方法

因为json(),和所有response methods一样,returns a Promise。

因此,与所有 Promise 一样,它是异步的,并且必须被 awaited 或与链式 then() 回调一起使用。

,

resp.json() 返回一个 Promise,因此您需要链接另一个 .then() 方法调用。从回调函数返回 resp.json() 可确保包装器 Promise 方法返回的 then() 解析为 resp.json() 返回的承诺。

第一个 Promise 方法返回的 then() 将被拒绝或完成,具体取决于 Promise 返回的 resp.json() 发生了什么。当第一个then()方法返回的promise完成时,执行第二个then()方法调用的回调函数。

如果您使用 async-await 语法,那么您将需要 await resp.json()

大佬总结

以上是大佬教程为你收集整理的在 JS 中使用 fetch 的问题全部内容,希望文章能够帮你解决在 JS 中使用 fetch 的问题所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: