1

In an angular service, we're exposing a function which provides a token and should be blocking, until the token is loaded.

the critical part in the service

....
    function getToken(){
        tokenPromise().then(
            function(token){ return token;},
            function(error){ return null;}
    }
....

How do I turn this to a blocking function code?

so that service.getToken(); is blocking/synchronious until token is there.

Returning a promise/callback is not a solution.

MemLeak
  • 4,456
  • 4
  • 45
  • 84

1 Answers1

2

In JavaScript, there're no blocking functions unless they're synchronous.

What you can do is returning the promise in getToken and continue it using promises with then:

getToken().then(function(token) {
    // Do stuff when I get the token
});

About the last update of OP...

Returning a promise/callback is not a solution.

This can't be decided by you. JavaScript can't block browser's UI thread, thus, your desired approach is absolutely impossible for now.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • so in this case, how to make it synchronous? because returning a promise does not solve the problem. – MemLeak Sep 24 '15 at 08:29
  • @MemLeak If you're performing an AJAX request, there's no chance to make it synchronous. AJAX is "Asynchronous JavaScript and XML", check the *asynchronous* part :( – Matías Fidemraizer Sep 24 '15 at 08:31
  • @MemLeak Returning the promise, solves the problem. Why not? The point is you need to leverage asynchronous programming or you're dead! :D – Matías Fidemraizer Sep 24 '15 at 08:31
  • @MemLeak It's my advise... don't get me wrong. UI and asynchronocity today is a *must have*. You want non UI tasks to don't freeze the UI, don't you? – Matías Fidemraizer Sep 24 '15 at 08:34
  • Because it shifts the problem to the next layer. nothing against async programming. this issue we have with waiting for the token showed up surprisingly ;) – MemLeak Sep 24 '15 at 08:35
  • @MemLeak That sounds like you should invest the work to restructure your code to work asynchronously – LionC Sep 24 '15 at 08:39
  • @MemLeak So you need to re-think your code :( JS won't provide a silver bullet here – Matías Fidemraizer Sep 24 '15 at 08:46