0

Below is the scenario:

( function($) {
    var currentPageUrl = window.location.href;
    var eciDisplayedCategoryCount;
    var eciDisplayCount = false;
    var eciTempCount = 0;
    if(currentPageUrl.indexOf('&page=') !== -1 ){
        var eciPageNum = currentPageUrl.substring(currentPageUrl.indexOf('&page=') + 6);

        if( eciPageNum ) {
            eciPageNum = parseInt(eciPageNum);
            for(i = eciPageNum - 1; i > 0; i--){
                var eciTempURL = currentPageUrl.substring(0, currentPageUrl.indexOf('&page=') + 6) + i;
                if( eciTempURL) {

                    $.get( eciTempURL, function( data ) {
                        // I want to access the eciTempCount
                        eciTempCount += $(data).find('ul.productGrid li.product').length;
                    });
                }
            }

            console.log( eciTempCount );
            // I want to access eciTempCount here but it is resulting to 0 even if the ajax is returning some value.
            if( eciTempCount ) {
                eciDisplayedCategoryCount = eciTempCount + 1;
                console.log( eciDisplayedCategoryCount );
                var eciDisplayCount = true;

            }
        }

    } else {
        var eciDisplayedCategoryCount = $('ul.productGrid li.product').length;
        if( eciDisplayedCategoryCount ){
            var eciDisplayCount = true;
        }

    }
    if( eciDisplayCount ) {
        $("#_eciCnt").html(eciDisplayedCategoryCount);
        $('.eci-product-counter').show(); 
    }   
})(jQuery);

I want to access eciTempCount outside of the ajax call since I have initialize in the first and changed inside the ajax call. But the value of the variable eciTempCount is not changed and resulting to 0.

prajwal_stha
  • 357
  • 3
  • 17
  • 1
    a better solution would be to use something like bluebird's `Promise.reduce` i think – Daniel Lizik Jan 05 '18 at 06:38
  • `$.get` is not a synchronous call by default. Hence you should not expect it to have been called in the next statement. – Spencer Wieczorek Jan 05 '18 at 06:40
  • the promise works async, much likely the code outside of it ends before the Promise gets its value. Depends what you need to do you could move the code which need to access the eciTempCount inside the Promise, otherwise you should explain in depth your needs. – Michele Dibenedetto Jan 05 '18 at 06:42
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Martin Schneider Jan 05 '18 at 07:00

0 Answers0