0

So, I have this code about an object

Obj.prototype.save = function (fn){

    var aabb = Obj.reEditName(this.name, function(newName) {
         return newName;
         // I also try the following
         var foo = newName; 
         return foo;
    });     
    console.log("aabb is  : "+aabb);

}

Obj.reEditName = function(name, fn){
    var name ? name : "TestingName";
    nameEditor(name,function(err, finalName) {
        return fn(finalName);
    });
}

Obj.reEditName works fine and I get a value back that I can get from newName.

But console.log("aabb is : "+aabb); gives back undefined.

I dont get why. I get a value and I return it, and aabb suppose to catch it. Why this isnt working? How I can pass newName back to aabb?

Thanks

user2860857
  • 549
  • 3
  • 10
  • 21

1 Answers1

0

The only reason you get undefined is because, newName is undefined... Let's take a look at your code.

Obj.prototype.save = function (fn){

    //I suppose here you are assigning aabb the result of reEditName.
    //because you are calling it...
    var aabb = Obj.reEditName(this.name, function(newName) {
         //you have a callback as a second parameter, and this callback recevied an argument (newName)...
         return newName;
         // I also try the following
         var foo = newName; 
         return foo;
    });     
    console.log("aabb is  : "+aabb);

}

The problem here is, when you are calling that callback from your reEditName method is not receiving that newName parameter, or it is receiving undefined for some other reason.

Possible solution:

Obj.reEditName = function(name, callback) {
  //you should call that callback with an argument, and return it...
  return callback('New name');
}
Miguel Lattuada
  • 5,327
  • 4
  • 31
  • 44
  • Yes my `reEditName` is like that. And if I do ` console.log("newName > "+newName);` inside the `var aabb = Obj.reEditName(this.name, function(newName) {` and before the ` return newName;` I get the value that I should have. Are you sure the problem is there? – user2860857 Jan 02 '16 at 18:56
  • I adjusted the answer's solution to fit that. – Miguel Lattuada Jan 02 '16 at 19:08
  • I also did what you said, but `console.log("aabb is : "+aabb);` still gives undefined. – user2860857 Jan 02 '16 at 19:09
  • I will test it right now. Thanks for your time. I dont know if it changes anything, but I added the definition of `Obj.reEditName `. Check my original question – user2860857 Jan 02 '16 at 19:39
  • return nameEditor and check if name editor return the second parameter which is the callback, as you do in reEditName... – Miguel Lattuada Jan 02 '16 at 19:45
  • Can you please edit your jsbin code, because I am lost? Thanks again – user2860857 Jan 02 '16 at 19:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/99551/discussion-between-miguel-lattuada-and-user2860857). – Miguel Lattuada Jan 02 '16 at 19:53