我有以下代码,它执行得很好。
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)
我可以做什么来解决这个问题?
同时返回承诺链
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
})
}