0

I want my sails controller to perform these steps:

-add word to Word table

-take the created word's ID and add it alongside with lesson's ID to a different table

module.exports = {
   add: function(req,res){
        var eng=req.param('english'), 
            pol=req.param('polish'),
            lessonID=req.param('lessonID');
        var wordID=this.create(eng,pol,lessonID);
        console.log(wordID);
    },

   create: function(eng,pol,lessonID){
           sails.models.word.create({
               english:eng,
               polish:pol})
           .exec(function (word){
            return word.id

   });
}
};  

I'm not sure how to return the wordID to the add function. Right now wordID is 'undefined'. I've tried changing the declaration of create to:

create(req,res)

and then return

res.json(200, { id: word.id });

but it didn't change anything. What is the proper way to deal with functions of this type?

K.W.
  • 59
  • 1
  • 10

1 Answers1

2

You have misunderstood the asynchronous nature of javascript.

var wordID=this.create(eng,pol,lessonID);
console.log(wordID);

Console.log will be executed immediately after the previous line.The database operation wont be complete by that time. You need to change the create method to accept a callback that needs to be executed once db operation is done.

add: function(req,res){
        var eng=req.param('english'), 
            pol=req.param('polish'),
            lessonID=req.param('lessonID');
        this.create(eng,pol,lessonID, (wordID) => { 
            console.log(wordID);
            return res.json({wordID});
        });
    },

   create: function(eng,pol,lessonID, callback){
           sails.models.word.create({
               english:eng,
               polish:pol})
           .exec(function (word){
            return callback(word.id);

   });
}
MjZac
  • 3,476
  • 1
  • 17
  • 28
  • There are still some issues to clear up... like `var wordID` will still be undefined because the create function itself doesn't return. And since `add` accepts `(req, res)`, it's probably supposed to do something with `res` like `res.send`, etc, and it should do that in callback of `create`. – arbuthnott Oct 09 '17 at 12:52
  • @arbuthnott my bad, just copy pasted the code. Forgot to remove variable assigning. Thanks for pointing it out. – MjZac Oct 10 '17 at 05:13