I'm doing an HTTP post, which returns single 10-15 character string. I want to assign this value to a temporary variable and use it while building up another larger string which will contain said 10-15 digit character string.
I've gotten this to work by making the temp variable ("ticket") global, which I don't like:
var ticket; // Global. Lame.
...stuff happens
getTicket("someUser", function(err) {
if(err)
{console.log("problem");}
else
{console.log(ticket);}
});
...other stuff happens
// Helper functions down here....
var getTicket = function (userName, callback) {
var user = userName;
request.post(
{
url: 'http://somewhere',
form: { 'username': user }
},
function(err, response, body) {
if(err) {
callback(err);
return;
} else {
ticket = body;
}
callback(null);
});
}
Can someone point me to the proper pattern to return the variable ticket in the POST's callback (or the body variable, whatever) ala:
_ticket = getTicket("someuser")
Thanks much.
You'd pass ticket as a parameter into your callback:
getTicket("someUser", function(err, ticket) {
if(err)
{console.log("problem");}
else
{console.log(ticket);}
});
function getTicket (userName, callback) {
var user = userName;
request.post(
{
url: 'http://somewhere',
form: { 'username': user }
},
function(err, response, body) {
if(err) {
callback(err);
return;
}
callback(null, body); // body contains the ticket
});
}
request.post is async, so there isn't a pattern that will get you something like:
_ticket = getTicket("someuser")