2014-10-04 69 views
-1

在下面的代碼中,我試圖在if塊中將truetest2()返回test1()
由於在test2(),可變flagfetch()success塊被設置爲true, 現在的問題是,由於骨幹fetch()異步調用,test2()將返回falsetest1()if塊(由於這一點,如果在test1()不能使用)和後來,一旦阿賈克斯呼叫完成test2()success設置flagtrue但這是沒有用的,因爲它已經返回falsetest1()只有在骨幹JavaScript抓取()調用完成後才需要運行代碼

那麼,請告訴我,如何把任何延遲/或僅在flag值被設置在取success塊 我試圖與_.delay()delay()但對我來說不是工作在test2()運行,如果塊。 請幫忙解決這個問題,因爲我花了很多日子,但無法弄清楚這個問題。

test1 :function() 
{ 
    var x = true; 
    if(x && this.test2())// call to test2 
    { 
     // run the code here 
    } 
}, 

test2: function() 
{ 
    var flag = false;// default value 
    noteCaseTeam = App.data.createBean('Module',{id:123});//Return the object of Team 
    noteCaseTeam.fetch(
    { 
     success:function() // working fine 
     { 
      flag =true;//setting flag to true 
      case_number_team = noteCaseTeam.get('name'); 
     } 
    }); // end of fetch function 
    if (flag) //Control is not reaching here due to "flag" default value 
    { 
     return true; 
    } 
    else { 
     return false; 
    } 
},// end of test2 

謝謝!!

+4

不要把像「緊急」你quesiton的稱號。這是無關緊要的,阻礙了人們看到你的問題。 Seprately:在尋求幫助時,花時間以可讀方式格式化您的代碼。你可以在你自己的代碼中使用你喜歡的任何支撐樣式或縮進,但是當要求其他人閱讀並且幫助你使用它時,你應該使用*隱含*通用的東西。 – 2014-10-04 09:43:41

回答

0

您不能使用異步調用返回Boolean

您更好的使用sync回調,運行您test1

this.listenTo(CaseTeam, 'sync', test1); 

CaseTeam應可你的代碼中。

如果你提供減少的測試用例,我會改進我的答案。

0

所有你需要的是學習jQuery的承諾的工作:http://code.tutsplus.com/tutorials/wrangle-async-tasks-with-jquery-promises--net-24135

test1 :function() 
{ 
    var x = true; 

    // Call test2() and wait it 
    this.test2().done(function (response) { 
     if (x) { 
      // run the code here 
     } 
    }); 
}, 

test2: function() 
{ 
    var noteCaseTeam = App.data.createBean('Module',{id:123});//Return the object of Team 
    return noteCaseTeam.fetch().done(
     function(response) { 
      case_number_team = noteCaseTeam.get('name'); 
     } 
    ); 
}, 
相關問題