TypeScript使用AWS SDK时如何提取并返回OutpostArn值
问题根因
- AWS SDK v2 接口默认采用异步回调模式执行,你当前直接返回的
OutpostArnData是请求发起阶段生成的Request实例,不是接口响应结果。 - 传入
getOutpost的回调函数会在网络请求完成后才异步执行,此时外层的GetOutpostArn方法早就执行完返回了,所以你能在回调里打印出ARN,但无法通过直接return Request对象拿到目标值。
修正后的实现代码
直接利用SDK Request对象自带的.promise()方法把回调式请求转成Promise,配合async/await以同步写法获取返回值即可:
import * as AWS from 'aws-sdk'; class Outpost { outpostId: string; region: string; constructor(outpostId: string, region: string) { this.outpostId = outpostId; this.region = region; AWS.config.update({ region: this.region }); } // 标记为异步方法,返回Promise包裹的ARN值 async GetOutpostArn(): Promise<string | undefined> { try { // await等待接口响应完成,拿到完整返回数据 const data = await new AWS.Outposts().getOutpost({ OutpostId: this.outpostId }).promise(); // 直接提取目标字段返回 return data.Outpost?.OutpostArn; } catch (err) { console.log(err, (err as Error).stack); throw err; } } } // 顶层调用需包裹在异步立即执行函数中(Node.js 顶层await需特殊配置,兼容写法用立即执行函数最稳妥) (async () => { const outpostArn = await new Outpost( 'op-0e32dade1930682b8', 'us-west-2' ).GetOutpostArn(); console.log(outpostArn); })();
关键改动说明
- 给
GetOutpostArn增加async标记,明确返回类型为Promise<string | undefined>,符合异步方法的返回规范 - 移除原有的回调传参,调用
.promise()把SDK回调式请求转为标准Promise对象,通过await阻塞等待响应返回后再取值 - 错误处理统一放到
try/catch块中,替代原回调内的错误判断逻辑 - 顶层调用通过异步立即执行函数包裹,解决全局作用域无法直接使用await的兼容问题
运行效果
执行代码后控制台将直接输出目标ARN值,不再返回Request对象:
arn:aws:outposts:us-west-2:280066404755:outpost/op-0e32dade1930682b8
内容的提问来源于stack exchange,提问作者Shepardos
相关产品推荐
相关产品推荐

