The AWS SDK documentation is not very clear about when/how/if asynchronous service calls can be made synchronous. For example, this page (https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html) says:
All requests made through the SDK are asynchronous.
Then on this page (https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-a-callback-function.html) it says:
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.
What it doesn't say though is how to wait for that callback function to finish.
For example, is this call asyncronous or synchronous?
new AWS.EC2().describeInstances(function(error, data) {
if (error) {
console.log(error); // an error occurred
} else {
console.log(data); // request succeeded
}
});
After describeInstances() has returned, can I assume the callback as been called? If not, how can I wait until it does?
Edit:
So I tried writing some async/await code as suggested, but it doesn't work:
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));
Now the way I see it I am waiting for the result of getVal() which is awaiting the Promise p, yet this is the result:
>>1 Promise { <pending> }
>>2 Promise { <pending> }
The script just exits without any promise finishing by the looks.
Is it ever possible in Node.js to get the return value of an async function/promise? I am scrathing my head over how simple this would be in Python.