0

Let's take a look at this:

protected getSettingByKey(key: string) : string {

    let ret = null;

    let api : BrowserAPI = Browser.getCurrentBrowserAPI();

    let setting = api.readSetting(this.getUUID() + "." + key, "true", (value:string) => {
        ret = key;
    });

    while (true) {
        if (ret != null) return ret;
        console.log("KEY IS NULL, SKIPPIN");
    }

}

This is a function that reads the browsers native data storage for settings and MUST block until the function readSetting() returns something.

I tried the above approach but it ends up being a dead loop.

I repeat, the function MUST, by all means BLOCK, it must NOT have any callback.

How to realize that?

I know this is an anti-pattern but that's the way it has to be.

Gala
  • 2,592
  • 3
  • 25
  • 33
  • You MUST not try to use blocking functions. I repeat, you can NEVER, by any means, BLOCK on an asynchronous functions. – Bergi May 08 '17 at 00:15
  • Your only choice is to rewrite `api.readSetting` to make it synchronous, such as changing the XMLHttpRequest call to be `async: false`. But as others have mentioned, you probably don't want to do that. Why do you think you do? –  May 08 '17 at 02:01

1 Answers1

2

If api.readSetting is asynchronous, you cannot do that.

From the multiple statements in the question that it must block and must not use a callback, I assume you're familiar with the fact that the solution here is not to block and to use a callback (directly, or via promises), as described here.

But without doing that, if you're calling an async function, you cannot make your function synchronous. You cannot synchronously wait for an asynchronous process to complete in browser-based JavaScript.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • That's what I was afraid of. I assumed there is some way to screw over the runtime (like you do 90% of the time in Web Development; `How can I trick the browser to do *this*?`) but I assume there is no way. Oh well. – Gala May 07 '17 at 17:07
  • @Gala: There isn't, no. *(I have to say that that characterization doesn't match my experience of web development.)* – T.J. Crowder May 07 '17 at 17:08