I currently have a function that is called from my router:
router.js:
var result = Api.getUser();
console.log("Result: " + result);
api.js
exports.getUser = function(req, result) {
request.get({
uri: URL + '/user/me/',
headers: {Authorization: 'bearer ' + req.user.accessToken},
json: true
}, function(e, r, body) {
console.log("e: " + e + " body: %j", body);
if(e) {
return "{error: true}";
} else {
return body;
}
});
};
The problem I am having is that I am getting the log "Result: undefined" first.
Is there a way to hold the function getUser from returning until the function for get finishes?
You are dealing with asynchronous code. There are a couple ways to solve this problem.
With A Promise
With A Callback
The nice thing about the promise API is that you only ever need to check for errors once, in your final
.catch
handler. In the callback style if you need to keep making additional asynchronous calls then you'll have to keep nesting callbacks and checkingif (err) return console.error(err)
in every single callback.You can't
return
from an async function, you use a callback:Promises are awesome, I would suggest looking into them. However, a simple callback will do the trick
api:
router: