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

后端 未结 8 725
暗喜
暗喜 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:22

    I would like to offer the following solution, which simply creates a nested function structure.

    // start with the last action
    var next = function() { context.succeed(); };
    
    // for every new function, pass it the old one
    next = (function(param1, param2, next) {
        return function() { serviceCall(param1, param2, next); };
    })("x", "y", next);
    

    What this does is to copy all of the variables for the function call you want to make, then nests them inside the previous call. You'll want to schedule your events backwards. This is really just the same as making a pyramid of callbacks, but works when you don't know ahead of time the structure or quantity of function calls. You have to wrap the function in a closure so that the correct value is copied over.

    In this way I am able to sequence AWS service calls such that they go 1-2-3 and end with closing the context. Presumably you could also structure it as a stack instead of this pseudo-recursion.

提交回复
热议问题