jeudi 2 avril 2015

Make chained functions wait for each other to execute

How do I make a chained function wait for the function before it, to execute properly?


I have this excerpt from my module:



var ParentFunction = function(){
this.userAgent = "SomeAgent";
return this;
}

ParentFunction.prototype.login = function(){
var _this = this;

request.post(
url, {
"headers": {
"User-Agent": _this.userAgent
}
}, function(err, response, body){
return _this;
})
}
}

ParentFunction.prototype.user = function(username){
this.username = username;
return this;
}

module.exports = parentFunction;


And this is from within my server:



var pF = require("./myModule.js"),
parentFunction = new pF();

parentFunction.login().user("Mobilpadde").exec(function(data){
res.json(data);
});


The problem is, that the user-function won't wait for login to finish (Meaning, it executes before the login returns _this). So how do I make it wait?


Aucun commentaire:

Enregistrer un commentaire