Typescript Return 承诺列表
Typescript Return List of Promises
我正在尝试从我们的 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)
这会记录一个空列表,因为控制台命令显然是 运行 在承诺之前。
我的目标是将帐户列表发送到我的打字稿应用程序中的不同功能(不同文件)。不知道该怎么做。
我建议您通读 https://javascript.info/async-await
- 异步采用函数 (....) -> T 到 (....) -> Promise
- await 接受对 T 的 Promise,但仅在异步函数内部
如果您在使用 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。因此,试图将其包含在这样的列表中是一个很大的禁忌。这样做可能发生的最糟糕的事情实际上是它起作用的时候。因为无法判断是什么原因导致它停止工作,如果一年后发生这种情况,祝你好运,弄清楚它为什么坏了或者为什么它首先起作用。
问题是您创建的函数 async () => { ... }
实际上 returns 一个 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);
});
我正在尝试从我们的 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)
这会记录一个空列表,因为控制台命令显然是 运行 在承诺之前。
我的目标是将帐户列表发送到我的打字稿应用程序中的不同功能(不同文件)。不知道该怎么做。
我建议您通读 https://javascript.info/async-await
- 异步采用函数 (....) -> T 到 (....) -> Promise
- await 接受对 T 的 Promise,但仅在异步函数内部
如果您在使用 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。因此,试图将其包含在这样的列表中是一个很大的禁忌。这样做可能发生的最糟糕的事情实际上是它起作用的时候。因为无法判断是什么原因导致它停止工作,如果一年后发生这种情况,祝你好运,弄清楚它为什么坏了或者为什么它首先起作用。
问题是您创建的函数 async () => { ... }
实际上 returns 一个 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);
});