Search code examples
javascriptfetchaddeventlistener

Issue with using fetch in JS


Here's the code:

        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;
    }

Why I should use .then after returning resp.json(). Why can't I just put resp.json() in a variable and get rid of the second .then (commented code)?


Solution

  • resp.json() returns a Promise, so you need to chain another .then() method call. Returning resp.json() from the callback function makes sure that the Promise returned by the wrapper then() method gets resolved to the promise returned by resp.json().

    The Promise returned by the first then() method will either be rejected or fulfilled depending on what happens to the Promise returned by resp.json(). Callback function of the second then() method call is executed when the promise returned by the first then() method is fulfilled.

    If you use async-await syntax, then you will need to await resp.json().