Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block on asynchronous functions in JavaScript

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.

like image 497
Ryan Li Avatar asked Dec 03 '10 13:12

Ryan Li


People also ask

Do async functions block?

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.

How do I stop async function?

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.

Can async be blocking?

Async is widely considered to be non-blocking.

How do you block a function in JavaScript?

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.


2 Answers

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");
like image 182
Šime Vidas Avatar answered Oct 11 '22 14:10

Šime Vidas


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");
}
like image 35
tomg Avatar answered Oct 11 '22 13:10

tomg