How do you structure sequential AWS service calls within lambda given all the calls are asynchronous?

后端 未结 8 788
暗喜
暗喜 2021-02-02 14:35

I\'m coming from a java background so a bit of a newbie on Javascript conventions needed for Lambda.

I\'ve got a lambda function which is meant to do several AWS tasks i

8条回答
  •  时光说笑
    2021-02-02 15:00

    I don't know Lambda but you should look into the node async library as a way to sequence asynchronous functions.

    async has made my life a lot easier and my code much more orderly without the deep nesting issue you mentioned in your question.

    Typical async code might look like:

    async.waterfall([
        function doTheFirstThing(callback) {
             db.somecollection.find({}).toArray(callback);
        },
        function useresult(dbFindResult, callback) {
             do some other stuff  (could be synch or async)
             etc etc etc
             callback(null);
    ],
    function (err) {
        //this last function runs anytime any callback has an error, or if no error
        // then when the last function in the array above invokes callback.
        if (err) { sendForTheCodeDoctor(); }
    });
    

    Have a look at the async doco at the link above. There are many useful functions for serial, parallel, waterfall, and many more. Async is actively maintained and seems very reliable.

    good luck!

提交回复
热议问题