【问题标题】:Node pattern for promisesPromise 的节点模式
【发布时间】:2014-03-13 21:10:27
【问题描述】:

我有一个节点问题。我想在其中调用一个数据访问对象和可能的其他对象,并在完成后渲染一个 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
 });

基本上,我想确保在使用数据呈现模板之前完成数据检索。目前,当渲染发生时,变量 store 没有被填充。我看过promises,它看起来很有希望。有没有人有一个巧妙的解决方案将我的代码示例转换为同步结构?

【问题讨论】:

    标签: javascript node.js design-patterns asynchronous promise


    【解决方案1】:

    这是一个承诺的答案(假设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

    【讨论】:

      【解决方案2】:

      您应该尝试使用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
                                     });
                                 }
                             }
                          );
      
      }
      

      【讨论】:

      • 谢谢,这正是我所需要的!
      猜你喜欢
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2017-07-28
      • 2017-02-23
      • 2018-10-21
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      相关资源
      最近更新 更多