nodejs Error: Callback was already called

nodejs Error: Callback was already called

我还是 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);
        }
    });

我想我明白了....

通过将 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);
}