javascriptasynchronous

A returned Promise with Fetch doesn't respond to .then()


I'm a bit confused here, this part of some async code isn't working. Here's the problem:

export async function active() {
    return new Promise(function(resolve,reject){
        fetch("https://api.spotify.com/v1/me", { //omitted headers to keep it clean
        }).then(response => console.log(response)) <-- This code runs, and will log a response
        .then(data => function(){ <-- but this won't
            console.log("This won't run either")
            if (data.status == 200) {
                console.log(true)
                resolve(data)
            } else {
                console.log(false)
                reject(data)
            }
        })
    })
}

Why isn't the second part running? Sorry, I'm a bit new to async/await


Solution

  • There are a few problems there

    1. .then(data => function(){ passes a function that returns a function into .then. You want either an arrow function or the function keyword but not both. Since all you're doing is returning a function (which nothing calls), you don't see the contents of that function run. Get rid of the function() part of that.

    2. There's no reason for new Promise in that code (and no reason for your function to be async), just use the promise chain you have from fetch. (More here.)

    3. Your first then handler returns undefined, because you're returning the result of console.log.

    4. Your code uses the name data where you're still dealing with a Response object whose body you haven't yet read. You probably want to read the body, via the .text(), .json(), or other similar body-reading methods.

    Instead:

    export function active() {
        return fetch("https://api.spotify.com/v1/me", { //omitted headers to keep it clean
        })
        .then(response => {
            if (!repsonse.ok) {
                throw new Error("HTTP status " + response.status);
            }
            return response.text(); // or `.json()` or several others, see #4 above
        });
    }
    

    Note I changed the check for success there slightly.