0

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

NeuronButter
  • 709
  • 1
  • 8
  • 24
  • what is `.this`? what is `data`? in the second .then? hint: it's the result of `console.log` which is `undefined` – Bravo Nov 03 '19 at 09:15
  • `data => function(){` you realise this returns a function which is never run? – Bravo Nov 03 '19 at 09:17
  • Why are you using the promise constructor anti-pattern and .then when you also already have promises and are in an async function? – jonrsharpe Nov 03 '19 at 09:23

1 Answers1

5

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875