Understanding the AWS SDK documentation can be a bit confusing when it comes to making asynchronous service calls synchronous. The page at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html states:
All requests made through the SDK are asynchronous.
However, on this other page (https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-a-callback-function.html), it explains:
The callback function will run once a successful response or error data returns. But it doesn't clarify how to ensure the callback finishes before proceeding.
For instance, in the code snippet below, is the call asynchronous or synchronous?
new AWS.EC2().describeInstances(function(error, data) {
if (error) {
console.log(error); // an error occurred
} else {
console.log(data); // request succeeded
}
});
Can we guarantee that the callback has been executed after describeInstances() is completed? If not, how can we manage that?
Edit:
Even attempting async/await strategies hasn't produced successful outcomes:
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));
Despite waiting for the result of getVal() which itself awaits the Promise p, the output remains:
>>1 Promise { <pending> }
>>2 Promise { <pending> }
This raises the question - is it ever achievable in Node.js to retrieve the return value of an async function/promise? This discrepancy between languages like Python where it seems so simple is indeed perplexing.