3

I understand how to use functions and also asynchronous functions with binding applying and calling. But I'm searching for a solution for the following for a long time.

To clarify why this is not a duplicate: I know how asynchronous calls work. I also understand why a variable isn't updated directly (due to the time difference between the start and the end of the call). My question simplified: is it possible to return to the original function and populate the variable?

Consider the following JavaScript pseudo code:

var returnedData = loadDataThroughAjax(url);

function loadDataThroughAjax(url)
{
    //here fires an xhrrequest using the specific url

    return xhr.readystatefunction = function()
    {
        if (this.reaystate == 4)
        {
            return this.responseText;
        }
    }


}

I would like the responsetext of the call to be loaded in the var returnedData in a single thread. I looked at some jquery code and there it looked like you could pull this of, or is the thing I'm asking impossible for an asynchronous call?

Mouser
  • 13,132
  • 3
  • 28
  • 54
  • 1
    You can't do that. Use promises. – SLaks Dec 21 '14 at 14:59
  • @SLaks Promises is experimental and not supported by IE. – Mouser Dec 21 '14 at 15:08
  • 1
    @Mouser then use a library that implements promises (like jquery) or write your own implementation. Either way, a promise is the way to go here. – prodigitalson Dec 21 '14 at 15:16
  • @prodigitalson Promises indeed look promising (pun intended). Also IE is going to support them soon. However I do not want to use libraries. JQuery promise implementation is flawed I read. Do you or somebody else have any lead on how to write a polyfill or know a good polyfill not library depended? – Mouser Dec 21 '14 at 15:35
  • 1
    While I know JQ promises are different they have worked form me just fine and since I almost always use JQ I have never had a reason to use something else with a proper implementation. There is this polyfill from [promisejs.org](https://www.promisejs.org): https://www.promisejs.org/polyfills/promise-6.0.0.min.js – prodigitalson Dec 21 '14 at 16:09

0 Answers0