Reputation: 193
This Lambda function does an http-request and then writes the data into DynamoDB. I'm wondering why the function is set asynchronously. Wouldn't it be the same if it weren't async? As far as I know, await tells the code to pause and to continue after httprequest() is done. Isn't that the same like running the code synchronously?
exports.handler = async (event) => {
try {
const data = await httprequest();
for (var i = 0; i < data.d.results.length; i++){
var iden = Date.now();
var identifier = iden.toString();
datestring.substring(4,6) + "-" + datestring.substring(6,8);
//add to dynamodb
var params = {
Item: {
id: identifier,
date: data.d.results[i].DAY_T,
},
TableName: 'DB'
};
await docClient.put(params).promise();
}
console.log('Document inserted.');
return JSON.stringify(data);
} catch(err) {
console.log(err);
return err;
}
};
Upvotes: 0
Views: 99
Reputation: 136164
async/await is syntactic sugar which makes writing code look similarly to how synchronous code would be written while maintaining all of the advantages of asynchronous code.
Essentially this:
var result = await doSomethingAsync();
console.log(result);
is actually this:
doSomethingAsync().then(result => {
console.log(result);
});
If you imagine doing lots of this it gets heavily nested very quickly. When you include error handling too, the then
/catch
method gets long and verbose. async/await lets you use try/catch in a more natural way - the same way you're used to for synchronous code.
Mix in the fact that your code is doing multiple await
within a loop, and I'd need to build up a list of promises and do a Promise.all
there too. It all gets pretty hard to write without making a mistake.
Upvotes: 1