我仍然是nodejs的新手并开发自己的异步函数。根据堆栈跟踪,我正在看,我被告知下面的代码被回调两次。特别是catch回调。
有没有更好的方法来构建这个,所以如果try中的多个变量爆炸,它只回调一次?
尽可能接近,因为所有的缓冲区读取都是异步完成的,如果出现多个错误,它们都会同时调用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);
}
});
答案 0 :(得分:0)
我想我已经明白了......
将cb(null, jsonData);
移动到try 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;
}catch(err){
return cb(err);
}
cb(null, jsonData);
}