I need to write a function in JavaScript, which returns a state from calling an asynchronous function. However, the caller only receives the value and no callback function is to be provided. I tried something like:
function getState() {
var ret = null;
asyncCall("request",
function() { ret = "foo"; } // callback
);
while (ret === null)
; // block on the asynchronous call
return ret;
}
However, the loop is never going to end…
Any ideas? Thank you.
In async functions, await blocks any code that follows from executing until the Promise has resolves, which means that our refactored code doesn't even start asyncThing2() until asyncThing1() has completed — that's not good.
You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.
Async is widely considered to be non-blocking.
In JavaScript, a block is denoted by curly braces. The space between the curly brackets is known as a block. For example, the if...else, do... while and for loop statements create blocks.
Why not just:
asyncCall("request", function() {
// here you can inspect the state
});
What's the point of the wrapper function?
Asynchronous functions work this way. If you want to block the execution, then use a synchronous call:
var state = syncCall("request");
I think you're looking for StratifiedJS, http://stratifiedjs.org It allows you to "orchestrate" your async code exactly like you wrote, BEWARE that it "writes" like synchronous code, it will NOT block the rest of your application. You can use it anywhere by loading the apollo js library.
This is how it would look like in Stratified JavaScript:
function getState() {
waitfor (var ret) {
// block on the asynchronous call
asyncCall("request", resume);
}
return ret;
}
of course there are modules/libraries that would just make it look like this: http://onilabs.com/modules#http
function getState() {
return http.get("request");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With