I'm tackling a project that requires me to use JavaScript with an API method call. I'm a Java programmer who has never done web development before so I'm having some trouble with it.
This API method is asynchronous and it's in a while loop. If it returns an empty array, the while loop finishes. Otherwise, it loops. Code:
var done = true;
do
{
async_api_call(
"method.name",
{
// Do stuff.
},
function(result)
{
if(result.error())
{
console.error(result.error());
}
else
{
// Sets the boolean to true if the returned array is empty, or false otherwise.
done = (result.data().length === 0) ? true : false;
}
}
);
} while (!done);
This doesn't work. The loop ends before the value of "done" is updated. I've done some reading up on the subject and it appears I need to use promises or callbacks because the API call is asynchronous, but I can't understand how to apply them to the code I have above.
Help would be appreciated!
function(result)in your case) to update the UI.async_api_calli already fired so it will pass, it won;t wait for the callback. Isn't that the purpose of async calls? Read this first stackoverflow.com/questions/748175/… maybe it will clarify the meaning of async functions. And because you cant update yet the done variable, !done is false and breaks the do while loop.async_api_callmultiple times unfortunately. This is because the method in question only processes data in batches of 50, and there are thousands of items I need to process, so I need to continue looping it until all items are processed.