我仍然对Node.js和开发自己的异步函数还是陌生的。根据堆栈跟踪,我正在查看,被告知以下代码被两次调用。特别是catch回调。
有没有更好的方法来构造这种结构,因此,如果尝试中的多个变量爆炸了,它只会回调一次?
据我所知,由于所有缓冲区读取都是异步进行的,如果发出多个错误,它们将几乎同时调用catch,从而导致我的错误。至少这是我唯一会想到的会导致此错误的事情,但是对于我自己的一生,我想不出办法。
function fun1(buffer_1, ushort_Type, cb){
cb = (typeof cb === 'function' ? cb : function(){} );
var jsonData = {};
try{
var uint_val1 = buffer_1.readUInt32LE(4);
var string1_val2 = buffer_1.toString('utf8', 12, 45);
var ubyte_val3 = buffer_1.readUInt8(46);
jsonData.Type = ushort_Type;
jsonData.val1 = uint_val1;
jsonData.val2 = string1_val2;
jsonData.val3 = ubyte_val3;
cb(null, jsonData);
}catch(err){
cb(err); //ln 393
}
}
错误堆栈跟踪。
FolderWatcher-3 [26/01/2017 17:16:45.898] [ERROR] Error: Callback was already called.
FolderWatcher-3 at C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:837:36
FolderWatcher-3 at C:\nodeCode\FolderWatcher\parse.js:116:10
FolderWatcher-3 at fun1 (C:\nodeCode\FolderWatcher\parse.js:393:4)
FolderWatcher-3 at C:\nodeCode\FolderWatcher\parse.js:114:8
FolderWatcher-3 at C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:4637:20
FolderWatcher-3 at replenish (C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:871:21)
FolderWatcher-3 at C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:881:15
FolderWatcher-3 at eachLimit (C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:4662:33)
FolderWatcher-3 at Object.<anonymous> (C:\nodeCode\FolderWatcher\node_modules\async\dist\async.js:930:20)
FolderWatcher-3 at process (C:\nodeCode\FolderWatcher\parse.js:87:10)
通话功能
//fun1
// var eventJSON = {};
if (eventJSON.fun1 === undefined) { eventJSON.fun1 = [];}
fun1(frameBuffer, ushort_FrameType, function(err, result){ //ln 114
if(err){
callback(err); //ln 116
}else{
eventJSON.fun1.push(result);
callback(null);
}
});
最佳答案
我想我已经解决了...
通过将cb(null, jsonData);
移动到try catch块的外面,使其发生在catch(err)之后而不是之前,我不再看到相同的错误。
function fun1(buffer_1, ushort_Type, cb){
cb = (typeof cb === 'function' ? cb : function(){} );
var jsonData = {};
try{
var uint_val1 = buffer_1.readUInt32LE(4);
var string1_val2 = buffer_1.toString('utf8', 12, 45);
var ubyte_val3 = buffer_1.readUInt8(46);
jsonData.Type = ushort_Type;
jsonData.val1 = uint_val1;
jsonData.val2 = string1_val2;
jsonData.val3 = ubyte_val3;
}catch(err){
return cb(err);
}
cb(null, jsonData);
}
关于node.js - nodejs错误: Callback was already called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878325/