当使用不依赖于async
库的第三方库时,以某种方式处理结果回调中的错误会调用其中一个并行任务中的任意回调。
例如
var async = require('async'),
bloomjs = require('bloom-js');
var client = new bloomjs.Client({url: "http://localhost:3005/api"});
async.parallel([function (cb) {
console.log('callback1');
client.find('usgov.hhs.npi', '1558490003', function (err, results) {
console.log('callback2');
if (err) return cb(err);
cb(results);
});
}], function (err, results) {
console.log('callback3');
throw "hello";
if(err) return console.dir(err);
console.dir(results);
});
生成输出
callback1
callback2
callback3
callback2
/Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:30
if (called) throw new Error("Callback was already called.");
^
Error: Callback was already called.
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:30:31
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:251:21
at /Users/untoldone/Source/async-demo/node_modules/async/lib/async.js:575:34
at /Users/untoldone/Source/async-demo/demo.js:9:21
at /Users/untoldone/Source/async-demo/node_modules/bloom-js/src/bloom.js:117:18
at IncomingMessage.<anonymous> (/Users/untoldone/Source/async-demo/node_modules/bloom-js/src/bloom.js:219:22)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
似乎callback2以某种方式用于处理callback3中的异常。但鉴于bloomjs
永远不会使用async
库,我不知道这是怎么回事。想法?
答案 0 :(得分:2)
我怀疑在bloomjs.Client.find
内部,回调代码包含如下内容:
try {
callback(false, result);
} catch (e) {
callback(e, result);
}
因此,当您的回调引发hello
错误时,上述代码会捕获此错误,并重新调用client.find
回调。这将再次调用cb()
,但async.js
检测到此循环并发出自己的错误信号。