0

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;
    }
};
4
  • Also, await docClient. --- To use await the function it is in needs to be async. Commented Oct 20, 2020 at 13:16
  • Not exaclty, no. await gives the JavaScript engine chance to run some other bit of JS rather than block waiting a response on the called function, just like promises. Commented Oct 20, 2020 at 13:22
  • developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/… Commented Oct 20, 2020 at 13:48
  • Isn't that the same like running the code synchronously no, it's still async. Commented Oct 20, 2020 at 13:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.