我正在尝试制作一个 Node.js 机器人,所以我找到了一个模块,安装了它并试用了它的示例代码。 现在,我有一个从 API 加载一些文本的异步函数。这是代码:
(async () => {
// Display user's balance
balance = kraken.api('Balance');
console.log(await balance);
})();
当我运行上面的代码时,这是我在命令提示符中得到的:
{
error: [],
result: { A: '2.0', BC: '0.005', BCA: '111' }
}
我怎样才能让它只记录其中的一个特定部分,它看起来像一个数组? 我试过做类似的事情(让它返回 2.0):
console.log(await balance.result.A)
但这似乎不起作用,因为它返回了这个:
(node:6604) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'A' of undefined
(node:6604) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
没有想法,需要帮助..谢谢!
最佳答案
你必须将你的 await 语句放在括号中,如下所示:
console.log((await balance).result.A);
这将异步获取余额,然后记录结果属性。
关于javascript - 如何抓取异步 JSON 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501724/