【问题标题】:AWS SDK wait for asynchronous call to complete?AWS SDK 等待异步调用完成?
【发布时间】:2019-10-30 19:33:45
【问题描述】:

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

通过 SDK 发出的所有请求都是异步的。

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

此回调函数在成功响应或错误数据返回时执行。如果方法调用成功,则数据参数中的回调函数可以获得响应的内容。如果调用不成功,则错误参数中提供有关失败的详细信息。

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

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

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

在 describeInstances() 返回后,我可以假设回调已被调用吗?如果没有,我怎么能等到它呢?

编辑:

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

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));

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

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

脚本只是退出,没有任何外观完成的承诺。

在 Node.js 中曾经有可能获得异步函数/承诺的返回值吗?我对这在 Python 中的简单程度感到头疼。

【问题讨论】:

  • 你绝对不能假设回调被调用(否则,你为什么甚至需要使用回调?)。 Probable duplicate

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


【解决方案1】:

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

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

检索数据的一种方法是使用 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 以等待该函数完成。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2020-10-04
  • 1970-01-01
  • 2020-01-02
  • 2016-03-16
相关资源
最近更新 更多