I asked question about how to run asynchronous method in loop. And I am now doing it in something like recursion.
How can asynchronous method in loop executed in sequence?
But now I can't get data pass to final callback(last line of my code), if db data is fetched successfully at second time.
- I notice the problem may be: second CallGetDB resolve() the data I want but first CallGetDB doesn't get that. Then first CallGetDB finished wihtout resolve anything. But I don't know how to solve it.
function CallGetDB(UID) {
return new Promise(function(resolve, reject){
GetDynamodb(UID)
.then((data)=> {
console.log("check before if"+JSON.stringify(data));
dbResponse = data;
resolve(dbResponse);
}
)
.catch((data)=> {
if(index++ < 2)
{
console.log("This is "+(index+1)+" try to get data from db with UID.");
setTimeout(function(){CallGetDB(UID);},100);
}
else
{
console.log("Database multi fetch failed");
resolve("Database multi fetch failed");
}
});
});
SendSQS(UID,event).then((data)=>{
return CallGetDB(data);
}).then((data)=>{
console.log("I am at most out:" +JSON.stringify(data));
response.body=JSON.stringify(data);
callback(null,response);
});