6

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

我使用catchand的方法的问题finallyfinally在第一次发生时调用它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)  

环境信息:

  • 当js:v3.1.0
  • 节点:v0.10.26
4

2 回答 2

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

笔记:

这其实不是一个小问题。当我说不是一个小问题时,我的意思是这是一个很难正确解决的大问题。这里有多种隐含行为和极端情况。

考虑阅读这个有点冗长的讨论。如果您愿意考虑 - 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.
})
于 2014-04-15T16:12:20.190 回答
0

根据Benjamin Gruenbaum的回答,我创建了一个when.map内部使用的替代解决方案,并将cache在处理finally所有承诺时触发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.mapsettle.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
于 2014-04-15T21:20:24.760 回答