AWS Lambda using Node JS on How to handle Synchronous for loop in Callbacks using Promise.
In this article we are going to see several steps which made us to solve problem.
How to add a promise to Node JS Function.
Promise is used in node JS in order to tell program to wait until we give further instruction. So when we use a promise to a function we either need to send resolve or reject back from the function based on promise parameters we use.
In Function call LoopMethod we have a promise with resolve and reject so we use .then () for resolve and .catch() for error
Now I will show how to write a promise inside Method (loopmethod) as per our example
Generally we need promises to methods having timeouts/api calls or external calls as js doesn't think it should wait for that to complete.
If you note my promise is returning resolve and reject and in exception I am sending reject and on completion I am sending resolve back.
That sends hint to parent call method in Figure 1 to either go to then block or catch block.
Now we have a problem as we need to loop this method of list of transactions we had created another promise on top to chain transactions synchronously.
Figure to show how to create Chain of Promises
This Explains how I have handled the chain of promises and using loopmethod to call synchronously. If we use promise.all() all the transactions run at same time. but with this they run sequential.
So Resolve tells back called method saying Function call is done. Reject says function call has errored out.
Bonus hint:
Make sure to avoid global variables as much as possible and in exceptions these variable can be used as local variables are not available.
Also To check whether its an array or object use the below method
if(Array.isArray(listData)){
}