Search code examples
javascriptjqueryajaxcallbackasynccallback

Two callback functions inside a function not called synchronously


    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.


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      
                }
            });
        });
    
    }