How to get parent function This inside child function using async.each - javascript

var self= this; //parent function context/this
async.each(smpleArray, sampleFunc, function(err){
// if any of the saves produced an error, err would equal that error
});
This is sample function :
var sampleFunc= function(){
var self = this; //window object
//do something
}
I want to fetch the parent's this context inside child.
But i am getting windows object there.
I tried:
async.each(smpleArray, sampleFunc, function(err){
// if any of the saves produced an error, err would equal that error
}.bind(this));
But its not working.
How to get the parent's self/this inside child function ?

You have to bind the context to the correct function, i.e. sampleFunc like this:
sampleFunc.bind(this)
So your example would be:
var sampleFunc = function () {
// this is set to parent function context/this
// do something
};
async.each(sampleArray, sampleFunc.bind(this), function (err) {
// if any of the saves produced an error, err would equal that error
});

Related

JS - Calling function from function not working

I have a function that gets called, and in it, I call another function called:
updatePerson(name)
For some reason it never activates when the function below is called. Everything else in the function works.
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
var matchName = String(results.data[0].first_name);
updatePerson(matchName);}
);
};
Has anyone got an idea what I am doing wrong?
If I run alert(matchName) I get Nick as a response.
If I run console.log(updateMap(matchAddress)) I get undefined
It could do with the fact that you're passing a parameter from a callback function. In Javascript, variables inside a Callback are not available outside the callback.
Try setting the value of String(results.data[0].first_name) to a variable declared outside of the updateName function (i.e a global variable) and then call the updatePerson function outside of update name, with the globally declared variable as a parameter. Like so
var globalMatchName = '';
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
globalMatchName =String(results.data[0].first_name);
}
);
updatePerson(globalMatchName)
}

return javascript variable from inside callback function

I am trying to get client.get to return the reply value so it can be used globally.It keeps saying undefined.any suggestions
var redis = require("redis");
var websocket= require("websocket");
var valuewanted;
websocket.on('message', function(data) {
if (data.type == "purchase" && data.price > 0) {
console.log("==========================================================");
console.log(data );
console.log("==========================================================");
client.get(p1, function(err, reply) {
var valuewanted = reply;
console.log(reply);
});
});
the console.log logs the value but if i try to log valuewanted it doesnt work.
Drop the var within the client.get function:
client.get(p1, function(err, reply) {
// valuewanted already defined above
valuewanted = reply;
console.log(reply);
});
If you use var within a function, it becomes scope-blocked to that function.
From mozilla:
The scope of a variable declared with var is its current execution
context, which is either the enclosing function or, for variables declared outside any function, global.
In this case, using var within that function redefines it within that function, and its scope becomes "the enclosing function". Hope this helps.

Callback losing scope of containing function

I have a code like that:
{
// other functions...
myFunction: function( item, options, callback ) {
var self = this;
// Both item and options variables are accessible here.
try {
var content = this.getContent( item );
} catch(ex) {
// Exception handling here....
}
editor.saveContent( content, function() {
// OPTIONS IS UNDEFINED HERE!
// ITEM IS UNDEFINED HERE!
// Callback, instead, is accessible!
if ( callback ) { callback() };
});
}
}
Problem is that inside the saveContent callback, I can access the callback variable, while any attempt in accessing the item, options and content vars are unsuccessful! Why is that?
You should supply the variable you are interrested in to the callback function like this:
editor.saveContent( content, function() {
if ( callback ) { callback(item, options) };
});
Via javascript closure, the item and options variable are available in the saveContent function.
Created fiddle to demonstrate (see console log).
The code you posted should work fine. But if that is really not working then try writing your code like this:
{
// other functions...
myFunction: function( item, options, callback ) {
var self = this;
// Store the reference in "this"
self.item = item;
self.options = options;
self.callback = callback;
// Both item and options variables are accessible here.
try {
self.content = this.getContent( item );
} catch(ex) {
// Exception handling here....
}
editor.saveContent( self.content, function() {
// Use them here
console.log(this.item, this.options, this.content);
// Callback, instead, is accessible!
if ( this.callback ) { this.callback() };
}.bind(self));
}
}
You have written var content inside the try-catch block. So it anyways can't be accessible outside the try-catch block.
editor.saveContent.call(this,content, function(){
//can access any variable defined in its parent scope
});

How to properly control the context when using d3.json event handler

I am trying to implement an asynchronous request with d3.js inside self-executing anonymous function.
Rather than saying d3.json(url, callback), I use d3.json(url) to first create the request object, then register a "load" event listener with xhr.on before starting the request with xhr.get.
Here is an example, in my object I have a render function that does render charts. I would like to call this render function once my data are loaded from an API.
The call is made properly but inside my render function i am not able to call my parseData function. It seems that I have lost the this context.
The console throw this exception : Uncaught TypeError: this.parseData is not a function
Does I make something wrong ? Thanks
(function() {
var Ploter = {
render: function(jsondata) {
this.parseData(jsondata); // where the error is raised
// draw the line chart
// ....
},
parseData: function(data) {
console.log(data);
},
init: function() {
this.bindEvents();
},
bindEvents: function() {
var self = this;
d3.json(this.DATAURL)
.on("load", this.render)
.on("error", function(error) { console.log("failure!", error); })
.get();
}
Ploter.init();
})();
Instead of passing the function directly, you can wrap it in another function, creating a closure. The inner function will be able to reference the value you stored in self, which refers to the original Ploter you're looking for:
bindEvents: function() {
var self = this;
d3.json(this.DATAURL)
.on("load", function(data) { self.render(data); })

Modifying instance variables from inner function in a prototype method

I'm attempting to model the data in my database as "classes" in server-side JavaScript (Node).
For the moment, I'm simply using the traditional constructor pattern with prototype methods where appropriate and exposing the constructor function as the entire module.exports. The fact that this is server side is unimportant to the core of the question, but I figured I'd provide it as reference.
The problem area of code looks like this:
User.prototype.populate = function() {
var that = this;
db.collection("Users").findOne({email : that.email}, function(err, doc){
if(!err) {
that.firstName = doc.firstName;
that.lastName = doc.lastName;
that.password = doc.password;
}
console.log(that); //expected result
});
console.log(that); //maintains initial values
};
Whenever I call this function, changes to the object do not persist once the findOne() has completed. I realize that the scope of this changes to the global object with new function scopes, so I maintained its reference as that. If console.log(that) from within the anonymous function, the data shows up in the properties of it as expected. However, if I log that once the function has finished, it maintains the state it had at the beginning of the function.
What's going on here and how I can I change instance variables as expected?
"However, if I log that once the function has finished, ..."
By this I assume you're doing something like this...
var user = new User
user.populate();
console.log(user);
If so, the console.log will run long before the asynchronous callback to .findOne() has been invoked.
Any code that relies on the response to findOne needs to be invoked inside the callback.
EDIT: Your update is a little different from my example above, but the reason is the same.
The entire reason for passing a callback to the findOne method is that it performs an asynchronous activity. If it didn't, there's be no reason for the callback. You'd just place the inner code directly after the call to findOne, as you did with the console.log().
But because it's asynchronous, the subsequent code doesn't wait to execute. That's why you're getting the unpopulated object in the console.
If you add a label to each console.log(), you'll see that they execute out of order.
var that = this;
db.collection("Users").findOne({email : that.email}, function(err, doc){
if(!err) {
that.firstName = doc.firstName;
that.lastName = doc.lastName;
that.password = doc.password;
}
console.log("inside the callback", that); // this happens Last!!!
});
console.log("outside the callback", that); // this happens First!!!
So it becomes clear once you observer the order of the console.log calls that the empty one is happening before the one inside the callback.
EDIT: You can also have your .populate() method receive a callback that is invoked inside the .findOne callback.
User.prototype.createNickName = function () {
this.nickname = this.firstName.slice(0,3) + '_' + this.lastName.slice(0,3);
};
// >>>------------------------------v----receive a function argument...
User.prototype.populate = function(callback_func) {
var that = this;
db.collection("Users").findOne({email : that.email}, function(err, doc){
if(!err) {
that.firstName = doc.firstName;
that.lastName = doc.lastName;
that.password = doc.password;
}
// all users will have the "createNickName()" method invoked
that.createNickName();
// ...and invoke it in the callback.
callback_func.call(that);
// By using .call(), I'm setting the "this" value
// of callback_func to whatever is passed as the first argument
});
};
// this user wants to log the firstName property in all caps
var user1 = new User;
user1.populate(function() {
console.log(this.firstName.toUpperCase());
});
// this user wants to log the the whole name
var user2 = new User;
user2.populate(function() {
console.log(this.firstName + ' ' + this.lastName);
});
// this user wants to verify that the password is sufficiently secure
var user3 = new User;
user3.populate(function() {
console.log(verify_password(this.password));
});

Categories