Question

    function sample() {

        var callback_1 = request1(function(response) {

            var Name = response.name;

        });


        var callback_2 = request2(function(response_1) {

                if (response_1.name === Name) {

                    // do something      
                });
        }

}

I've two callback functions as shown above, callback_1 & callback_2 which requests a JSON from the service.

The callback_2 is called before callback_1 and variable Name is shown as undefined. Any help much appreciated,

How can I let callback_1 executed before callback_2 so that variable Name is not undefined.

Was it helpful?

Solution

Try this:

function sample() {

    var callback_1 = request1(function(response) {
        var Name = response.name;

        var callback_2 = request2(function(response_1) {
            if (response_1.name === Name) {
                // do something      
            }
        });
    });

}

OTHER TIPS

jQuery ajax request return a deferred object (assumming request1 and request2 are ajax calls of some sort). Take a look at http://api.jquery.com/category/deferred-object.
You can use something along the lines of:

function sample() {
    var Name;
    var callback_1 = request1(function(response) {
        Name = response.name;

    });


    callback_1.then(
        callback_2 = request2(function(response_1) {

            if (response_1.name === Name) {

                // do something      
            };
        })
    );

} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top