简体   繁体   English

节点js TypeError:callBack不是函数

[英]node js TypeError: callBack is not a function

Here two functions 这里有两个功能

function pushArray(data, array){
    var index = -1;
    array.forEach(function(item) { 
        if(item.name === data.name) { 
            index = array.indexOf(item);
            console.log('found existing item at ' + index);
        }
    });
    if(index >= 0){
        array[index] = newItem;
    }else {
        array.push(newItem);        
    }
}

function showData(data, array){
    try {
        if(data){
            console.log('data \n');
            console.log(data.toString());
            console.log(array);
        }
    } catch (error) {
        console.log("Showing data caused error: " + error);
    }
}

This is how the callbacks are called 这就是回调的调用方式

fsReadFile(csvPath1, pushArray. array1);
fsReadFile(csvPath1, showData, array1);

function fsReadFile (filePath, callBack, array) {
    fs.readFile(filePath, function(err, data) {
        if(err) {
            console.error(err);
        }
        callBack(data, array);
    });
}

the show data shows either data and array when send as callback but the pushArray doesn't work as callback as node js complains show数据在作为回调发送时显示数据和数组,但由于节点js抱怨pushArray不能作为回调工作

    array.forEach(function(item) {
         ^

TypeError: Cannot read property 'forEach' of undefined

Is that more an callback or array issue ? 那是回调还是数组问题? If anyone could explain the root cause ? 是否有人可以解释根本原因?

 fsReadFile(csvPath1, pushArray(). array1); 

You are calling pushArray immediately , with no arguments (so array is undefined ), and the return value is passed as the second argument. 您将立即调用pushArray ,不带任何参数(因此arrayundefined ),并且将返回值作为第二个参数传递。 Don't call it there . 不要在那叫它

Then you have a typo where you have a . 然后您有一个错字,而您有一个错字. instead of a comma (so you try to read the array1 property of the return value of pushArray() and don't pass a third argument at all). 而不是逗号(因此,您尝试读取pushArray()的返回值的array1属性,并且根本不传递第三个参数)。

fsReadFile(csvPath1, pushArray, array1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM