samedi 21 février 2015

Implement future() after splitting one function into two

I have a function which uses future and it works perfectly fine. I am now splitting the get request and the response into two separate functions so it will be easy to read and debug when needed. The splitting of this works fine but my client does not wait for the returned value, how can I implement the future in the split function.


Eg. deep function using future and it returns value when available to client



var request = function (perm_data) {
var f = new future();
request.get('http://ift.tt/1w8OVQJ', {
oauth: {consumer_key:'somekey',
token: perm_data.oauth_token,
token_secret: perm_data.oauth_token_secret
}
}, function response(error, response, body) {
if (!error && response.statusCode === 200) {
var bodyToJson = parser.toJson(body, options)
var userId = bodyToJson.user.id
return f.return(userId)
}
else {
f.throw(error)
}
})
return f.wait()
}


The following is how I prefer my code. It is easy on the eye and good for long term maintenance. It does work I have checked. However, I get the value printed on the server, but the client does not wait for the return valued like my code above. Is there a way to implement future()?



var request = function (perm_data) {
request.get('http://ift.tt/1w8OVQJ', {
oauth: {consumer_key:'somekey',
token: perm_data.oauth_token,
token_secret: perm_data.oauth_token_secret
}
}, response)
}


var response = function (error, response, body) {
if (!error && response.statusCode === 200) {
var bodyToJson = parser.toJson(body, options)
var userId = bodyToJson.user.id
return userId
}
else {
return (error)
}
}

Aucun commentaire:

Enregistrer un commentaire