I have a question about how to perform an asynchronous task in a while-loop until some condition is met. This is more of a theoretical question but I can see how this could be an issue in some scenarios.
I'll try demonstrate the problem at an example (I'm using JavaScript here, but you can use any language):
I could have a device and I want to hold my application until that device has reached a specific state. If the method with which I can getrieve with state of the device is synchronouse, the code could look like this:
// Hold until the desired state is reached
var state = false;
while (!state) {
state = device.getStateSync();
}
// [...] continue the program
My question now is: How can I transform this code when all I get from the device is a asynchronous getState function? The code should work no matter how long the execution time of the call is and should keep in mind that I'm working on limited memory and stack size.
// [...] This would call the async function in a loop and crash the program
while (!state) {
// [...] something
device.getStateAsync(function(newState) {
state = newState;
});
// [...] something else
}
This one post that I found has a recursive solution (http://blog.victorquinn.com/javascript-promise-while-loop). While this is a nice solution, at some point it will run into stack-size problems, if the loop is called too often.
Right now I have the gut feeling that there might be no solution. Do you know of any way to do this? Or do you know how to prove that there is no way to do it? Feel free to include more complex concepts like Threads, Promises or Futures.
Please bear in mind, that this is a theoretical question and the example is for a situation where I have no way of changing the framework (or device) I am working with.
Thanks for every response and idea!
Pedro
whileloop. Just have the callback invoke thegetStateAsyncuntil thestateshould disallow it. There's no call stack size issue at all.