javascript - AWS SDK 等待异步调用完成?

标签 javascript aws-sdk aws-sdk-js asynchronous-javascript

AWS SDK 文档对于何时/如何/是否可以使异步服务调用同步不是很清楚。例如,这个页面 ( https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html ) 说:

All requests made through the SDK are asynchronous.

然后在这个页面(https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-a-callback-function.html)上写着:

This callback function executes when either a successful response or error data returns. If the method call succeeds, the contents of the response are available to the callback function in the data parameter. If the call doesn't succeed, the details about the failure are provided in the error parameter.

但它没有说明如何等待回调函数完成。

例如,这个调用是异步的还是同步的?

new AWS.EC2().describeInstances(function(error, data) {
  if (error) {
    console.log(error); // an error occurred
  } else {
    console.log(data); // request succeeded
  }
});

在 describeInstances() 返回后,我可以假设回调已被调用吗?如果没有,我如何才能等到它出现?

编辑:

所以我尝试按照建议编写一些异步/等待代码,但它不起作用:

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
let data = null;
r = s3.listBuckets({},function(e,d){
    data = d;
})
p=r.promise();
console.log(">>1",p);

async function getVal(prom) {
    ret = await prom;
    return ret;
}
console.log(">>2",getVal(p));

现在我看到它的方式是等待 getVal() 的结果,它正在等待 Promise p,但这是结果:

>>1 Promise { <pending> }
>>2 Promise { <pending> }

脚本只是退出,看起来没有任何 promise 。

在 Node.js 中曾经有可能获得异步函数/promise 的返回值吗?我绞尽脑汁想这在 Python 中会多么简单。

最佳答案

异步调用完成后,作为参数传递的函数将启动。该函数有两个参数(错误、数据)。

  • 第一个参数是“错误”。如果有错误,此参数包含错误消息。否则它是空的。
  • 第二个参数是数据。如果没有错误,此变量包含您需要的数据。

检索数据的一种方法是使用 promise 。

const getDescribeInstances = new Promise((resolve, reject) => {
  new AWS.EC2().describeInstances(function(error, data) {
    if (error) return reject(error);

    resolve(data);
  });
}

async function functionToDoSomethingWithTheData(){
  try {
    const describeInstances = await getDescribeInstances();
  }
  catch(error) {
    //handle error
  }
}

通过将 AWS 函数包装在一个 promise 中,您可以将结果存储在一个变量中。

它需要放在一个异步函数中(如示例所示)并在它之前调用 place await 以等待函数完成。

关于javascript - AWS SDK 等待异步调用完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627376/

相关文章:

javascript - 如何将 1 年添加到开始日期以获取 javascript 中的结束日期

amazon-web-services - 使用 API 在 AWS Workspaces 上创建用户

java - 如何使用 S3AsyncClient 从 S3 读取 JSON 文件

amazon-web-services - 如何在 NextJS 中设置 AWS-SDK 凭证

amazon-web-services - 如何在Node AWS SDK代码中使用AWS ECS任务角色

amazon-dynamodb-streams - 当 ShardIteratorType 设置为 LATEST 时,dynamoDBStreams getRecords() 返回空记录

javascript - 在页面中随机淡入和淡出图像?

javascript - jQuery .load() 另一个包含 prism.js 的页面

javascript - 如何在href中运行javascript?

ruby - 使用 Shoryuken (ruby) 的 Amazon SQS 自定义重试延迟