我想使用该when.map
功能来处理一些数据。处理完数据后,我需要做一些清理工作(例如,将当前使用的数据库连接释放回连接池)。
我使用catch
and的方法的问题finally
是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)
环境信息:
- 当js:v3.1.0
- 节点:v0.10.26