2014-03-13 126 views
1

我有一個節點問題。我想打電話給其內部數據訪問對象和其他可能的,一旦完成渲染玉模板承諾的節點模式

喜歡的東西:

provider1.getData(args, function(error, results) { 

    /* do something with each result element */ 
    for(int i = 0l i < results.length; i++) { 
    provider2.getData(args, function(error, items) { 

     store.push(items); 
    }); 
    } 
}); 
/* Here I want to ensure that the above operations are complete */ 
result.render(.... , { 
    data:store 
}); 

基本上,我希望確保數據檢索完成之前我渲染模板與數據。目前,渲染髮生時,變量存儲不會被填充。我看過promises看起來很有前途。有沒有人有一個整潔的解決方案將我的代碼示例轉換爲同步結構?

回答

0

您應該嘗試使用async庫。

provider1.getData(args, function(error, results) { 

    /* do something with each result element */ 
    async.each(results, 
         function(result, cb) { // called for each item in results 
          provider2.getData(args, function(error, items) { 

            store.push(items); 
            cb(error); 
          }); 
         }, 
         // final callback 
         function (err) { 
          if (!err) { 
          /* Here I want to ensure that the above operations are complete */ 
           result.render(.... , { 
            data:store 
           }); 
          } 
         } 
        ); 

} 
+0

謝謝,這正是我需要的! – avrono

3

這是一個承諾答案(假設Bluebird)。我認爲這是有很多清潔:

// convert to promise interface, it's possible to do this on a single method basis 
// or an API basis, it depends on your case - it's also _very_ fast. 
Promise.promisifyAll(Object.getPrototypeOf(provider1.prototype)); 
Promise.promisifyAll(Object.getPrototypeOf(provider2.prototype)); 

//note the async suffix is added by promisification. 
provider1.getDataAsync(args).then(function(results) { 
    return Promise.map(results,provider2.getDataAsync.bind(provider2)); 
}).then(function(results){ 
    //results array here, everything is done and ready, 
}); 

由於總是與承諾,如果你有一個錯誤,你可以簡單地throw