如何使用catch,最后使用when.map

时间:2014-04-15 16:03:46

标签: javascript node.js promise when-js

我想使用when.map函数来处理一些数据。 处理完数据后,我需要进行一些清理(例如,将当前使用的数据库连接释放回连接池)。

我使用catchfinally的方法存在的问题是,当第一个finally发生时调用reject,而其他映射仍在进行中。

那么我怎么能等到所有映射承诺都完成,这样就可以进行保存清理。

  require('when/monitor/console');
  var when = require('when');

  function testMapper(value) {
    console.log('testMapper called with: '+value);
    return when.promise(function(resolve, reject) {
      setTimeout(function() {
        console.log('reject: '+value);
        reject(new Error('error: '+value));
      },100*value);
    });
  }

  when.map([1,2,3,4],testMapper)
  .then(function() {
    console.log('finished')
  })
  .catch(function(e) {
    console.log(e);
  })
  .finally(function() {
    console.log('finally')
  });

输出

 testMapper called with: 1
 testMapper called with: 2
 testMapper called with: 3
 testMapper called with: 4
 reject: 1
 [Error: error: 1]
 finally
 reject: 2
 [promises] Unhandled rejections: 1
 Error: error: 2
     at null._onTimeout (index.js:9:14)

 reject: 3
 [promises] Unhandled rejections: 2
 Error: error: 2
     at null._onTimeout (index.js:9:14)

 Error: error: 3
     at null._onTimeout (index.js:9:14)

 reject: 4
 [promises] Unhandled rejections: 3
 Error: error: 2
     at null._onTimeout (index.js:9:14)

 Error: error: 3
     at null._onTimeout (index.js:9:14)

 Error: error: 4
     at null._onTimeout (index.js:9:14)  

Environmentinformation:

  • whenjs:v3.1.0
  • node:v0.10.26

2 个答案:

答案 0 :(得分:2)

最好的选择是与when.settle一起使用,并在他们解决时结算所有承诺,而不是在他们履行时,所以你可以手动检查哪一个做得好,哪一个没有。

var arrayOfPromises = array.map(testMapper);
when.settle(arrayOfPromises).then(function(descriptors){
     descriptors.forEach(function(d){
         if(d.state === "rejected"){
             // do cleanup for that promise, you can access its rejection reason here
             // and do any cleanup you want
         } else{
            // successful results accessed here
            console.log("Successful!", d.value);
         }
     })
});

注意:

这实际上不是一个小问题。当我说一个小问题时,我的意思是这是一个很难解决的问题。这里有多种隐含行为和边缘情况。

考虑阅读this somewhat lengthy discussion。 如果您愿意考虑--Bluebird有一个实验promise-using分支,允许指定处理器,这样可以让您轻松地完成此操作。

你可以这样做:

using(pool.getConnectionAsync().disposer("close"), function(connection) {
   return connection.queryAsync("SELECT * FROM TABLE");
}).then(function(rows) {
    console.log(rows);
});

或者在多资源情况下:

var a = Promise.cast(externalPromiseApi.getResource1()).disposer("close");
var b = Promise.cast(externalPromiseApi.getResource2()).disposer("close");
using(a, b, function(resource1, resource2) {
    // once the promise returned here is resolved, we have a deterministic guarantee that 
    // all the resources used here have been closed.
})

答案 1 :(得分:0)

基于 Benjamin Gruenbaum 的答案,我创建了一个内部使用结算的when.map替换,并在所有承诺时触发cachefinally已经处理了map

  var settle = {};
  var arrayMap = Array.prototype.map;

  settle.map = function(array, f) {

    var arrayOfPromises = arrayMap.call(array,function(x) {
      return when.resolve(x).then(f);
    });

    return when.settle(arrayOfPromises)
    .then(function(descriptors) {
      var result = [];

      descriptors.forEach(function(descriptor) {
        if( descriptor.state === 'rejected') {
          throw descriptor.reason;
        }

        result.push(descriptor.value);
      });

      return result;
    });
  };

当我现在用原始代码中的when.map替换settle.map时,输出/执行顺序就像我要求的那样:

 testMapper called with: 1
 testMapper called with: 2
 testMapper called with: 3
 testMapper called with: 4
 reject: 1
 reject: 2
 reject: 3
 reject: 4
 [Error: error: 1]
 finally