2014-05-07 26 views
0

我有不斷循環的函數,如果它發現更多然後1個結果中的第一方法的每一個循環:funcion循環如果發現一個以上結果

schedule: function() { 
    Meteor.call('getOneUser', Session.get("selectedEmployee"), function (error, mainResult) { 
    if (error) { 
     console.log(error.message); 
    } else if (mainResult != undefined) { 
     _.each(mainResult.schedule, function (schedules) { 
     Meteor.call('timezoneChanger', schedules.from, function (error, result) { 
      if (error) { 
      console.log(error.message); 
      } else { 
      schedules.from = result; 

      Meteor.call('timezoneChanger', schedules.to, function (error, result) { 
       if (error) { 
       console.log(error.message); 
       } else { 
       schedules.to = result; 

       Session.set('foundSchedule', mainResult.schedule); 
       } 
      }); 
      } 
     }); 
     }); 
    } 
    }); 

    console.log("a"); 
    return Session.get('foundSchedule'); 
} 

以下代碼日誌「一」無限次。但是當我在我的mongoDB中只有一個時間表集合時,它只運行一次(mainResult.schedule)。

模板只是看起來是這樣的:

<template name="employee_schedule"> 
    Schedule:<br> 
    {{#each schedule}} 
    <div>{{from}} - {{to}}</div> 
    {{/each}} 
</template> 
+2

神聖莫里,這是一些*積極*縮進! – Bucket

+1

而一個教科書如何更高效的支撐和承諾的例子都會使這個更具可讀性。 – jfriend00

+0

@DesertIvy,現在好點了嗎? :-) –

回答

0

的可能的問題是反應性的,假設你在喜歡的模板助手的反應環境中使用此方法。

在每次更新後,您都會使用Session.set('foundSchedule', ...),這會觸發每個使用Session.get('foundSchedule')的反應方法的重新運行 - 您在最後一行中執行此操作。要查看這是否是問題,請註釋掉Session.set行並檢查日誌,無限循環應該消失。

要解決此問題,請在一個幫助程序中爲數組提供服務,並在數組項的上下文中使用另一個輔助程序中設置的fromto參數。這也應該顯着降低您的代碼複雜度。

+0

我不明白,如果我不像上面那樣調用方法調用,則在調用返回之前方法不會完成並更改它們的值。另外,如果我從_.each(mainResult.schedule ...)得到一個結果,而不是在我得到兩個結果時如何實現這個功能? – jt123

+0

您是否嘗試評論該行?發生了什麼? –

+0

它停止循環,但我也沒有得到任何值返回到我的模板。 – jt123