How to pass one function result to another function in Node.js

Viewed 1167

I have function to create inside of it; I am checking if it's created or not by calling another helper function, but I'm unable to return that helper function result; if I did I can get only as undefined.

Here is my function :

//controller / form.js;
exports.createFormsElement = (req, res) => {
  console.log("Post a Elements: " + JSON.stringify(req.body));
  formById = formsHelper.formById("1");
  console.log("formById" + formById);
  res.send({ result: formById ? formById : "empty" });
  return;
};

//helper/forms.js 
module.exports = {
    formById: function(idForms) {
        Forms.findOne({
            where: {
                idForms: idForms
            },
            attributes: ['idForms']
        }).then(data => {
            return data;
        });
    }
}
2 Answers

Problem with your code is that you have an async operation i.e a database call. Within your function you are expecting a synchronous return from that which dosen't work well as you need to wait for I/O to finish. A solution would be to

//controller / form.js;
exports.createFormsElement = async (req, res) => {
  console.log("Post a Elements: " + JSON.stringify(req.body));
  const formById = await formsHelper.formById("1");
  console.log("formById" + formById);
  res.send({ result: formById ? formById : "empty" });
};

//helper/forms.js 
module.exports = {
    formById: function(idForms) {
        return Forms.findOne({
            where: {
                idForms: idForms
            },
            attributes: ['idForms']
        })
    }
}

note that there is changes in both helper/forms.js and controller/form.js async is however supported on later versions of node 7.6 or higher natively or you might have to use a transpiler or callbacks.

try this:

function fOne () {
  return 'test'; // "return" passes the function result to the calling function
}

function fTwo() {
  console.log(fOne());
}
Related