1

I am writing some code for a program, but I'm not able to figure out how to assign the output of a fetch to a variable. Here's my code:

const fetch = require('node-fetch');

var totalNumOfPages;

fetch('https://api.hypixel.net/skyblock/auctions')
    .then(res => res.json())
    .then(totalPages => totalNumOfPages = totalPages)

console.log(totalNumOfPages)

The output is undefined, rather than the value of "totalPages" taken from the api. How can I assign the value of totalPages to the var totalNumOfPages.

  • This seems like you're doing the correct thing. What happens if you log the `totalPages` directly inside the last `.then()`? Does it still log undefined? – Phoenix1355 May 10 '21 at 13:36
  • Nope, it logs the correct value if I do console.log. – Saransh Agrawal May 10 '21 at 13:40
  • Ahh, I was noticing that something similar was happening when I logged totalNumOfPages inside a .then() as well as logging it outside, It would print undefined, then the desired value, which I thought was odd. How do I fix the problem then? – Saransh Agrawal May 10 '21 at 13:45
  • My previous comment disappeared for some reason. Look at the linked questions at the top of your own. Your question has been marked as a duplicate since someone else already asked the same question. The answers to the other questions should help you. – Phoenix1355 May 10 '21 at 13:47
  • See the duplicate answers, but basically fetch is asynchronous, this console.log gets run before fetch completes. If you put the call in a async function and put await in front of fetch it will print. Side note, I would return the value instead. `const totalNumOfPages = await fetch(...)` – Geoffrey Bourne May 10 '21 at 13:50

0 Answers0