2016-02-25 4 views
8

मुझे कोड निष्पादन के दौरान errorCount संपत्ति को बढ़ाने में समस्या हो रही है। मेरी समस्या यह है कि $.ajax अनुरोध के अंदर हो रहा है, अधिक विशेष रूप से addError() विधि।जावास्क्रिप्ट ऑब्जेक्ट काउंटर अपेक्षित के रूप में वृद्धि नहीं कर रहा है

यदि मैं errorCount की वर्तमान गणना की जांच करने के लिए नीचे दिए गए कोड का उपयोग करता हूं तो यह हमेशा 0 देता है, भले ही मैंने मैन्युअल रूप से कोई त्रुटि उत्पन्न की हो। लेकिन addError() पर कॉल करने के बाद AJAX विधि के अंदर और फिर errorCount के मान की जांच करें, यह 1 जैसा दिखाना चाहिए। मैंने गलत क्या किया?

function test(a, b, c) { 
    this.settings = a; 
    this.formData = b; 
    this.search = c; 
    this.errorCount = 0; 
} 

test.prototype = { 
    constructor: test, 
    queueEmails:function(settings, formData, search) { 
     var url = '/example-url-endpoint'; 
     var data = {postData: settings + "&" + formData + "&" + search}; 
     this.sendRequest(url, data); 
    }, 
    queueCalls:function(settings) { 
     var url = '/example-url-endpoint2'; 
     this.sendRequest(url, settings); 
    }, 
    addMessage:function(response) { 
     flashMessage(response.Message, response.Result); 
    }, 
    addError:function() { 
     this.errorCount++; 
    }, 
    sendRequest:function(url, data) { 
     var blah = this; 

     j$.ajax({ 
      type: "POST", 
      url: url, 
      data: data, 
      dataType: 'json', 
      success: function(data) { 
       response = JSON.parse(data); 
       if(response.Result != 'error') { 
        blah.addMessage(response); 
       } else { 
        blah.addMessage(response); 
        blah.addError(); 
        console.log(blah.errorCount); 
       } 
      }, 
      error: function(e, textStatus, errorThrown) { 
       blah.addError(); 
       console.log(blah.errorCount); 
       alert("There was an error creating the queue"); 
      } 
     }); 
    } 
} 
+1

इसका कारण यह है कॉल अतुल्यकालिक है, यह 0 से पहले त्रुटि देता है 1. –

उत्तर

3

समस्या आप एक अतुल्यकालिक (AJAX) कॉल कर रहे हैं:

var boom = new test(settings, formData, search); 
console.log(boom.errorCount); 
boom.queueCalls(settings); 
console.log(boom); 
console.log(boom.errorCount); 

यहाँ वस्तु कोड है। जब आप queueCalls फ़ंक्शन को कॉल करते हैं, तो यह AJAX कॉल करता है, फिर आपके console.log स्टेटमेंट चलाता है। यह तब तक इंतजार नहीं करता जब तक कि AJAX कॉल नहीं किया जाता है, और आपको कंसोल स्टेटमेंट चलाने के लिए आपकी त्रुटियां प्राप्त हुई हैं। यदि आप ऐसा करना चाहते हैं, तो jQuery documentation for .ajax() देखें, और या तो अपने AJAX कॉल को एसिंक्रोनस न करें, या अपने कंसोल स्टेटमेंट को .done() ईवेंट हैंडलर में डालें जो AJAX कॉल पूर्ण होने के बाद आग लग जाएगी।

enter image description here

+1

कि चाल किया था पता चलता है। धन्यवाद! – Yamaha32088

संबंधित मुद्दे