如何从 Fetch Api 返回值[重复]

问题描述 投票:0回答:1

我有以下代码,它执行得很好。

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)

我不想通过控制台记录数据,而是想返回保存数据的变量 parsedData。我尝试进行类似的修改,但它给了我一个未定义的值。

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)

我可以做什么来解决这个问题?

javascript fetch-api
1个回答
1
投票

同时返回承诺链

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
  })
  
}
© www.soinside.com 2019 - 2024. All rights reserved.