2014-03-13 179 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