0

I'm attempting to coax JavaScript into synchronous behaviour, but I've so far failed.

I've tried 30 or more different methods, and here is the latest attempt, based on another answer, here on StackOverflow:

function fnc () {
    $.ajax({
        type: 'GET',
        url: "libraries/resources/data.json",
        dataType: 'json',
        success: function (data) {
            ...
            objSomething = {
                ...
            };
    },
        error: function () {}
    });
}
fnc().then(function(objSomething) {
    google.maps.event.addDomListener(window, 'load', function(){ initialize(objSomething); });
}).catch(function(objSomething) {
    ...
});

However, I'm getting an error:

TypeError: undefined is not an object (evaluating 'fnc().then')

Most of the methods I've tried have resulted in similar errors.

As for the Google Maps code, it does work (although not always, due to the asynchronous nature of the code execution).

It's worth noting that while I'm able to write complex code from scratch, when it comes to the underlying mechanics, I'm not that proficient.

I'm using jQuery 2.2.2, via the Google API CDN.

Community
  • 1
  • 1
Wayne Smallman
  • 1,690
  • 11
  • 34
  • 56
  • 4
    Your `fnc` function doesn't return anything, so you can't do `fnc().then()`... – XCS Apr 15 '16 at 13:44
  • @Cristy, based on the examples I've tried, some had a return statement, some didn't. I've tried a return statement and it doesn't work. I'd appreciate an example of what — in your opinion — should work. – Wayne Smallman Apr 15 '16 at 13:46
  • @WayneSmallman "It doesn't work" doesn't provide enough information to diagnose. If a function doesn't return anything, you can't call anything on its return value--if there's an example suggestion you can, that example is incorrect. – Dave Newton Apr 15 '16 at 13:47
  • You should take a look over basic `JavaScript` function calls and `async` functions. After that you should be able to solve your issue pretty quickly. – XCS Apr 15 '16 at 13:48

2 Answers2

3

This is a solution you are looking for.

   function fnc () {
        var dfd = jQuery.Deferred();
        $.ajax({
            type: 'GET',
            url: "libraries/resources/data.json",
            dataType: 'json',
            success: function (data) {
                ...
                objSomething = {
                    ...
                };
             dfd.resolve(objSomething);
        },
            error: function (error) { dfd.reject(error); }
        });

        return dfd.promise();
    }

    $.when(fnc()).then(function(objSomething) {
        google.maps.event.addDomListener(window, 'load', function(){ 
           initialize(objSomething); 
        });
     }, function(error){
       //Handle Error
     });
P. Janowski
  • 306
  • 1
  • 6
0

use $.ajax function you can use the then function. Refer the following link:

http://wildermuth.com/2013/8/3/JavaScript_Promises
Maths RkBala
  • 2,207
  • 3
  • 18
  • 21