I want to call an async function from within a do while loop and exit only if the function doesn't return a value. Is there a way to manage this without having to actually wait outside the callback?
Here's the code that obviously always exits in the first loop since the function hasn't called back yet, when the while () is evaluated:
var i = 0;
do {
var foundListing;
if (i) {
listing.slug = listing.slug + '-' + (i + 1);
}
listingService.getListingBySlug(listing, function(error, pFoundListing) {
if (error) {
return callback(util.errorParser(error));
} else if (Object.keys(pFoundListing).length) {
foundListing = pFoundListing;
i++;
}
});
//Do I have to wait here???
} while (foundListing && Object.keys(foundListing).length);
For Clarification: The point here is to generate a unique slug. If the slug already exists, i append a number and check again if it exists. When I get to the number that doesn't exist yet, I'm done.
Update: I found a way using recursion. I posted the working snippet as an answer.
listingService.getListingBySlugat each iteration of the loop, at maximum speed javascript can execute that loop. Are you sure is what you want to do?foundListingis empty in the beginning thewhile()part always evaluates to false in the first loop because it is set within the callback, which hasn't been executed yet. Either way, that's not what I want. I want to only enter the loop again, if the a listing has been found inlistingService.getListingBySlug