0

the problem here is that I have a function that uses an ajax request to return a value to the myBookmarks variable. This variable needs to be assigned before the remainder of the JavaScript (not shown) can execute. So setting async: false does the trick, but in Firefox, I get:

Use of XMLHttpRequest's withCredentials attribute is no longer supported in the synchronous mode in window context.

I have been pursuing a solution using a setTimeout, but the anonymous function in the setTimeout cannot return the value of bookmarks to the upper level function.

So the question is, how to pause execution within the index() function and return the value of bookmarks back to the upper level myBookmarks var without using async: false?

var myBookmarks = index();

function index() {
    var bookmarks = false;

    $.ajax({
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        async: false,
        url: BOOKMARKS_URL,
        contentType: 'application/json',
        dataType: 'json',
        success: function(data){
            if (!data.errors) {
                // INDEX SUCCESS
                bookmarks = data;
            } else {
                // INDEX FAILURE
            }
        }
    });

    return bookmarks;
}
jerome
  • 4,809
  • 13
  • 53
  • 70
  • 2
    If you cannot make a synchronous request, then there is no way to return the response from a function. See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) for alternative solutions (you basically have to restructure your code to work with callbacks/promises). – Felix Kling Aug 16 '13 at 14:00
  • Welcome to the wonderful world of **async**! You can't do that. – SLaks Aug 16 '13 at 14:01

1 Answers1

1

how to pause execution within the index() function and return the value of bookmarks back to the upper level myBookmarks var without using async: false

You can't. One option is to provide a callback, and call that when the async function completes:

function index(successCallback) {

    $.ajax({
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        async: false,
        url: BOOKMARKS_URL,
        contentType: 'application/json',
        dataType: 'json',
        success: function(data){
            if (!data.errors) {
                // INDEX SUCCESS
                successCallback(data)
            } else {
                // INDEX FAILURE
            }
        }
    });
}

Then call it like

index(function(bookmarks){
  // do something with bookmarks
});
Jamiec
  • 133,658
  • 13
  • 134
  • 193