简体   繁体   中英

Callback not a function NodeJS

I'm quite new in NodeJS, but I'm struggling also with concept of passing variables / objects between functions. I appreciate any help on what I am doing wrong.

Please, consider this code:

incoming request:

{ 
    sender: '32165498732165845',
    text: 'shopping',
    originalRequest: 
    { 
        sender: { id: '32165498732165845' },
        recipient: { id: '87971441647898' },
        timestamp: 1488196261509,
        message: { mid: 'mid.1488196261509:c7ccb7f608', seq: 36372, text: 'shopping' } 
    },
    type: 'facebook' 
}

Extracting relevant variables:

var userId = request.sender;
var listName = request.text;

bot.js:

var listOps = require('./listops/test.js');
listOps.setActive(function (userId, listName, callback) {
    console.log ('Here I expect a callback!');
    return callback; // This will send the message back to user.
});

listops/test.js:

exports.setActive = function(userId, listName, callback) {
    var message = "User number " + userId + " asks to create a list with name " + listName + ".";
    console.log(userId);
    console.log(listName);
    callback (message);
}

Now my issue is that in listOps.js the outcome of both console logs is not the value I expect, it says [Function] and undefined . Therefore I suspect, that this is a root cause for error message [TypeError: callback is not a function] .

I'm using Claudia.js in Lambda.

Try changing your bot.js to the following:

var listOps = require('./listops/test.js');

listOps.setActive( userId, listName, function (message) {
      console.log ('message holds the result set in listops/test.js!');
});

If you want to process the message afterwards, you simply could pass it to another function:

bot.js :

var listOps = require('./listops/test.js');

var processor = function(userId, listName, message){
     ... process as desired
}

listOps.setActive( userId, listName, function (message) {
      console.log ('message holds the result set in listops/test.js!');
      process(userId, listName, message);
});

this is happening because in your listops/test.js file you are defining a function exports.setActive = function(userId, listName, callback) which accepts three arguments userId listName and callback while you call this function in the bot.js file you are passing only a function listOps.setActive(function (userId, listName, callback) { which is illegal as expected by the definition of the setActive function. You need to call this function as below

listOps.setActive(userId, listName, function() {
                //your stuffs here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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