如何将承诺的结果保存到变量?
How to save results of a promise to a variable?
我需要从 API 中获取一些 JSON 数据并将结果分配给一个变量。我可以在控制台中看到数据数组,但 [abc] 始终设置为 Pending promise。
我尝试分配 [abc] 而不是记录 [data] 或简单地返回 [data] 但它不起作用。
理想情况下,我还想停止执行以下代码,直到我获得所需的数据,但使用我拥有的代码,文本在数据
之前被记录
async function fetchData()
{
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData()
.then(data => console.log(data));
console.log('This should not be logged if 'abc' does not have the data i need')
(data => console.log(data)) ..>> 这里的数据是我需要的数组,但我不知道如何给变量赋值。
我在互联网上寻找了很多解决方案,但找不到任何有用的方法。
编辑 1:
如果我分配:
让 abc = 等待 fetchData()
如果没有 then 语句,它会抛出这个错误:
未捕获的语法错误:await 仅在异步函数中有效
如果我然后删除 await 关键字 returns Promise 没有解决它。
应该是这样的
async function fetchData(){
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().
为了使 await
关键字起作用,它必须位于 async
函数内。所以你需要先把你的代码包装在一个异步函数中,比方说一个主函数,然后调用它。示例:
async function fetchData() {...}
async function main() {
let abc = await fetchData();
console.log(abc);
}
main();
我需要从 API 中获取一些 JSON 数据并将结果分配给一个变量。我可以在控制台中看到数据数组,但 [abc] 始终设置为 Pending promise。
我尝试分配 [abc] 而不是记录 [data] 或简单地返回 [data] 但它不起作用。 理想情况下,我还想停止执行以下代码,直到我获得所需的数据,但使用我拥有的代码,文本在数据
之前被记录async function fetchData()
{
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData()
.then(data => console.log(data));
console.log('This should not be logged if 'abc' does not have the data i need')
(data => console.log(data)) ..>> 这里的数据是我需要的数组,但我不知道如何给变量赋值。
我在互联网上寻找了很多解决方案,但找不到任何有用的方法。
编辑 1:
如果我分配: 让 abc = 等待 fetchData() 如果没有 then 语句,它会抛出这个错误: 未捕获的语法错误:await 仅在异步函数中有效
如果我然后删除 await 关键字 returns Promise 没有解决它。
应该是这样的
async function fetchData(){
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().
为了使 await
关键字起作用,它必须位于 async
函数内。所以你需要先把你的代码包装在一个异步函数中,比方说一个主函数,然后调用它。示例:
async function fetchData() {...}
async function main() {
let abc = await fetchData();
console.log(abc);
}
main();