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);
});
Your promise isn't resolving in the event of an error and an
index
lower than 2. Here:At that point, your promise will never fulfill or reject as the original promise never gets fulfilled and can't
resolve
the JSON data nor does it hit yourelse
branch.It becomes an unresolved promise (a promise stalled indefinitely). It will work in the event thatGetDynamodb
fulfills on the first attempt though.You can fix this by fulfilling the promise inside the
if
branch:That being said, you probably shouldn't be wrapping promises like this. This is a somewhat similar approach to yours:
You can also use a closure for scoping retries, so you have a proper scope for your
index
variable:Which you can now use like:
CallGetDB(2)(data)
Wrapping
GetDynamodb(UID)
in anew Promise
is an anti-pattern since it returns a promise.Following adds a
retries
parameter with a default toCallGetDB()
and either returns a new promise in thecatch()
when retries are within limits.... or throws a new error to get caught in followingcatch()