6

when.map関数を使用してデータを処理したいと考えています。データが処理された後、いくつかのクリーンアップを行う必要があります (たとえば、現在使用されているデータベース接続を解放して接続プールに戻します)。

catchandfinally を使用する私のアプローチの問題は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)  

環境情報:

  • whenjs: 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の回答に基づいて、内部で解決する使用の代替を作成し、のすべての約束が処理されたときにandwhen.mapをトリガーします。cachefinallymap

  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 に答える