2014-01-07 21 views
0

針對節點中的npm模塊嘗試並獲取這些函數以同步執行:saveFlightDetails需要saveFlight首先完成,這需要saveItem首先完成...並且每組這些在循環迭代到下一組數據之前,需要完成3個功能。使用node.js中的wait.for問題

我有一個for循環,裏面有下面的代碼,用我的數據設置迭代兩次(2個航班)。

function saveData(app, data, i){ 

      var Item = app.get('models').Item; 
      var Flight = app.get('models').Flight; 
      var FDeparture = app.get('models').FDeparture; 
      var FArrival = app.get('models').FArrival; 
      var currentItem = [], 
       currentFlight = []; 

      wait.for(saveItem, data, Item, i, currentItem, currentFlight); 
      console.log('currentItem: ' + currentItem); 
      wait.for(saveFlight, data, Flight, i, currentItem, currentFlight); 
      console.log('currentFlight: ' + currentFlight); 
      wait.for(saveFlightDetails, data, FDeparture, FArrival, i, currentItem, currentFlight); 


    } 

    wait.launchFiber(saveData, app, data, i); 

和saveItem,saveFlight和saveFlightDetails轉到其他將數據保存到db的函數。這是saveItem但其他人看起來非常相似:

function saveItem(data, Item, i, currentItem, currentFlight){ 
console.log('Entered item function.'); 
Item.create({ 
    ... 
    }).success(function(item){ 
    console.log('Created item.'); 
    currentItem = item; 

    }); 
} 

出於某種原因,我似乎無法解釋,循環迭代兩倍預期,但輸出是:

Reached saveItem function. 
Reached saveItem function. 
Item saved. 
Item saved. 

的saveFlight和saveFlightDetails功能arent被稱爲與current.tem和currentFlight的那些console.logs,但saveItem運行正確...

我認爲這將調用saveItem並等待,直到它完成,然後調用saveFlight並等待,然後調用saveFlightDetails並等待。然後迭代。我究竟做錯了什麼?

感謝您的幫助

回答

0

好的,我找到了答案。對於那些可能覺得這很有用的人,因爲wait.for中沒有很多示例文檔,所以我需要創建更多的光纖。因此,我不需要一根光纖用於一個功能saveData,而是用3個wait.for調用它,我需要3根光纖,每個都有自己的功能,每個光纖都有一個wait.for調用。僞代碼如下:

function save1(args){ 
    wait.for(asyncfunction1, args); 
    console.log('save1 done.'); 
} 

function save2(args){ 
    wait.for(asyncfunction2, args); 
    console.log('save2 done.'); 
} 

function save3(args){ 
    wait.for(asyncfunction3, args); 
    console.log('save3 done.'); 
} 


wait.launchFiber(save1, app, data, i); 
wait.launchFiber(save2, app, data, i); 
wait.launchFiber(save3, app, data, i);