我正在尝试从我们的AWS账户中获取组织账户ID的列表。
我有以下代码
const acc_list: string[] = [];
(async () => {
const orgs = await aws.organizations.getOrganization();
orgs.accounts.forEach(account =>
acc_list.push(account.id))
})()
console.log(acc_list)
这会记录一个空列表,因为显然控制台命令在promise之前运行。
我的目标是我要将帐户列表发送到我的打字稿应用程序中的其他功能(不同的文件)。不知道该怎么做。
答案 0 :(得分:0)
我建议您通读https://javascript.info/async-await
如果您在异步/等待方面遇到问题,请直接使用promise api。
const accountIDs = (org) => orgs.accounts.map(account => (account.id))
const fetchAccountIDs = async () => accountIDs(await aws.organizations.getOrganization())
const promisedAccountIds = fetchAccountIDs()
promisedAccountIds.then(ids => console.log(ids))
关于使用promise编程的一个大原则是它们包含的数据永远不会离开promise。因此,尝试在这样的列表中捕获它是一个很大的问题。可能发生的最糟糕的事情实际上是它起作用时。因为无法确定是什么原因导致它停止工作,并且如果从现在起一年后发生这种情况,请弄清楚为什么它坏了或者为什么它首先起作用了。
答案 1 :(得分:0)
问题在于您创建的函数async () => { ... }
实际上返回了一个Promise
,您仍然需要等待。因此,将异步代码包装到这样的异步lambda中没有意义,因为代码块保持异步。我可以建议你
这个tutorial。
解决方案取决于问题的上下文,可能是整个块应该是异步的,例如:
async function printAccountIds() {
const orgs = await aws.organizations.getOrganization();
const accountIds = orgs.accounts.map(account => account.id);
console.log(accountIds);
}
或者您也可以订阅承诺,例如:
aws.organizations.getOrganization().then(orgs => {
const accountIds = orgs.accounts.map(account => account.id);
console.log(accountIds);
});