承诺的节点模式

我有一个节点问题。 我想调用一个数据访问对象,可能还有其他的内容,一旦完成渲染一个Jade模板

就像是 :

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 }); 

基本上,我想确保数据检索完成之前,我与数据呈现模板。 目前,渲染发生时,variables存储不会被填充。 我看过看起来很有希望的承诺。 有没有人有一个整洁的解决scheme将我的代码示例转换为同步结构?

你应该尝试使用asynchronous库。

 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 }); } } ); } 

这是一个承诺答案(假设蓝鸟 )。 我认为这是一个更清洁:

 // 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