如何将获取响应存储在javascript变量中



对基本问题感到抱歉。我试图使用fetch从api获取数据,并希望将该响应存储到javascript变量中,但它并没有像我预期的那样工作我的代码-

async function fun() {
var a = "initial";
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(data => {
a = data;
console.log(a);
})
await console.log("Response => ", a);
}

输出-响应=>初始

做这件事的正确方法是什么。

您可能需要在fetch之前添加await

async function fun() {
var a = "initial";
await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(data => {
a = data;
console.log(a);
})
console.log("Response => ", a);
}

您所做的工作超出了需要。您的fetch调用应该返回promise。然后当你想访问数据时,你awaitfun调用,并且可以读取响应

async function fun() {
return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
}
const data  = await fun();

或者,如果你只想使用async/await,你可以做一些类似的事情

const fun = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return response.json()
}
await fun();
let darth = fetch('https://jsonplaceholder.typicode.com/users')
let java = []
darth.then(res => res.json()).then((log) => java.push(log))
const user = java.flat().map(res => res)

这适用于chrome上的开发人员控制台,但不适用于visualstudio代码。奇怪的我能够获取数据并将其放入常量