如何将promise的结果保存到变量中? [英] How to save results of a promise to a variable?

查看:1175
本文介绍了如何将promise的结果保存到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从API提取一些JSON数据并将结果分配给变量.我可以在控制台中看到数据数组,但是[abc]始终设置为Pending promise.

I need to fetch some JSON data from an API and assign the result to a variable. I can see the array of data in the console, but [abc] is always set as a Pending promise.

我尝试分配[abc]而不是记录[data]或仅返回[data],但是它不起作用. 理想情况下,我也想停止执行以下代码,直到获得所需的数据为止,但是使用我拥有的代码,文本会在数据之前记录下来

I've tried to assign [abc] instead of logging [data] or simply returning [data] but it's not working. Ideally, I would also want to stop the execution of the following code until I get the required data but with the code I have, the text gets logged before the 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)).. >>这里的数据是我需要的数组,但是我不知道如何在变量上赋值.

(data => console.log(data)) ..>> here the data is the array I need but I have no idea on how to assign on a variable.

我在互联网上寻找了许多解决方案,但是找不到任何可以帮助您的东西.

I've looked for many solutions on the internet but I couldn't find anything that could help.

如果我分配: 让abc =等待fetchData() 如果没有then语句,则会引发此错误: 未捕获的SyntaxError:等待仅在异步函数中有效

If I assign: let abc = await fetchData() without the then statement it throws me this error: Uncaught SyntaxError: await is only valid in async function

如果我随后删除了await关键字,它将返回Promise而没有解决该问题.

If I then remove the await keyword it returns Promise without having it resolved.

推荐答案

为使await关键字起作用,它必须位于async函数内.因此,您需要先将代码包装在一个异步函数中,比如说一个主函数,然后再调用它.示例:

In order for await keyword to work, it must sit inside a async function. So you need to wrap your code in a async function first, let's say a main function, then call it. Example:

async function fetchData() {...}

async function main() {
  let abc = await fetchData();
  console.log(abc);
}

main();

这篇关于如何将promise的结果保存到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆