Search code examples
javascriptnode.jspromisebluebird

Bluebird promise variable: 'undefined is not a function'


I have a nodejs express server and I'm working with bluebird Promises for synchronize all the async stuff.

Everything works fine on localhost using an AWS RDS MySQL database, but when I uploaded the server to my AWS EC2 instance I have found a problem with this function:

var Promise = require('bluebird');
var db      = require('./db');

exports.matchValue = function (params) {
    return new Promise(function(resolve, reject) {
        var findValue = new Promise(); 
        if (params.find.includes(".")) {
            var aux = params.find.split(".");
            var matchBy = {};
            if (aux[0]) matchBy.a = aux[0];
            if (aux[1]) matchBy.b = aux[1];
            findValue = db.getValues1(params.limit,params.page,matchBy);
        }
        else {
            findValue = db.getValues2(params.limit,params.page,params.find);
        }
        findValue
        .then(function(result) {
            resolve(result);
        })
        .catch(function(err) {
            reject(err);
        });
    }); 
}

I have declared the variable findValue as a new Promise because depending of the if condition, it will receive the value of a different database query function (this functions return a Promise).

When I call this function, this is the result: "undefined is not a function".

I understand that this behaviour happens because it executes first findValue.then() than the if/else block code, and as the variable is undefined it can be a function.

I thought that declaring a variable as a new Promise it will wait until the return of the function assigned to this variable finishes, but actually is not happening.

What am I doing wrong? Can someone help me?

Thank you in advice!!


Solution

  • Your .matchValue() function should simplify to :

    exports.matchValue = function(params) {
        var aux = params.find.split('.');
        return (aux.length < 2) ? db.getValues2(params.limit, params.page, params.find) : db.getValues1(params.limit, params.page, { 'a': aux[0], 'b': aux[1] });
    };
    

    With this, .then(function(result) certainly won't throw because that line has disappeared, but the function's caller might well throw instead. If so, then you must (again) suspect that either db.getValues1() or db.getValues2() doesn't return a promise on the EC2 server; try logging the returned value/object to see what it is.