0

I have the following code and it executes perfectly.

var website = "youtube.com"
const getViews = (website) => {
  fetch("/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=" + website, {
    headers: {
      "X-Api-Key": "hidden"
    }
  })
  .then((res) => res.json())
  .then((data) => JSON.stringify(data))
  .then((data) =>{
    let parsedData = JSON.parse(data)
    console.log(parsedData)
  })
  
}

getViews(website)

Instead of console logging the data I wanted to return the variable parsedData that holds the data. I tried modifying the like so but it gives me a value of undefined.

var website = "youtube.com"
const getViews = (website) => {
  fetch("/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=" + website, {
    headers: {
      "X-Api-Key": "hidden"
    }
  })
  .then((res) => res.json())
  .then((data) => JSON.stringify(data))
  .then((data) =>{
    let parsedData = JSON.parse(data)
    return parsedData
  })
  
}
let holdData = getViews(website)
console.log(holdData)

What can I do to fix this?

1 Answers1

1

Return the promise chain as well

const getViews = (website) => {
  return fetch("/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=" + website, {
    headers: {
      "X-Api-Key": "hidden"
    }
  })
  .then((res) => res.json())
  .then((data) => JSON.stringify(data))
  .then((data) =>{
    let parsedData = JSON.parse(data)
    return parsedData
  })
  
}
Bugs bunny
  • 137
  • 1
  • 4
  • This won't return the variable; it will return a promise. Call to `getViews` function will either need to be _awaited_ or call `then` method on it: `getViews(...).then(data => { ... })`. In short, OP can't do what they are trying to do - at-least not reliably. – Yousaf Aug 26 '21 at 05:15
  • Oh yeah right but this is usually what you get unless you use some sort of promise wrapper – Bugs bunny Aug 26 '21 at 05:22