Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript返回承诺列表_Typescript_Pulumi - Fatal编程技术网

Typescript返回承诺列表

Typescript返回承诺列表,typescript,pulumi,Typescript,Pulumi,我正在尝试从我们的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) 它记录了一个空列表,

我正在尝试从我们的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)
它记录了一个空列表,因为控制台命令显然是在承诺之前运行的


我的目标是将帐户列表发送到typescript应用程序中的不同函数(不同文件)。不知道怎么做

我建议你通读一遍

  • async接受一个函数(..)->T到(..)->Promise
  • wait接受对T的承诺,但仅在异步函数中
如果您在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))

用承诺编程的一条重要规则是,它们所包含的数据永远不能离开承诺。因此,试图将其记录在这样的列表中是一个很大的禁忌。这样做最糟糕的事情实际上是当它起作用时。因为无法判断是什么原因导致它停止工作,如果一年后发生这种情况,那么祝你好运,弄清楚它为什么会坏,或者为什么它一开始工作。

问题是,你创建的函数
async()=>{…}
实际上返回了一个你仍然需要等待的
承诺。因此,将异步代码包装到这样的异步lambda中没有意义,因为代码块仍然是异步的。我可以推荐你
这个

解决方案取决于问题上下文,可能是整个块应该是异步的,如:

异步函数printAccountIds(){ const orgs=等待aws.organization.getOrganization(); const accountIds=orgs.accounts.map(account=>account.id); console.log(accountid); }
或者你也可以只订阅承诺,比如:

aws.organizations.getOrganization().then(orgs=>{
const accountIds=orgs.accounts.map(account=>account.id);
console.log(accountid);
});

这是否回答了您的问题?因此,我真的需要在每次需要列表时调用该函数,并在此时对其进行迭代?重复调用
promisedAccountIds。然后(ids=>…)
将不会导致额外的网络流量。只有
fetchAccountIDs()
将触发网络事件/延迟。是的,答案似乎是将整个块包装在一个异步函数中。