I am trying to create a helper function which takes in an ID, requests a URL from a 3rd party API server, and returns the body of the response to the function that called it..
const request = require("request-promise");
module.exports = {
get: function(styleID, callback) {
let url = 'api/' + styleID ;
request(url, (body => {
if (body.substr(0, 1) !== '<') {
return JSON.parse(body);
} else {
return {error: '404'};
}
}))
}
}
Example Usage:
router.get('/obj/:id', function(req, res) { var collection = db.get().collection('obj');
collection.find({
'id': req.params.id
}).toArray((err, docs) => {
if (docs.length === 0) { // if nothing is found
resp = getObjects.get(req.params.id); // << Usage here
collection.insert(resp);
res.json(resp);
} else {
res.json(style[0]);
}
});
});
For some reason this keeps returning undefined. Something about asynchronous programming traps, timing, and callback hell. What is the approach to doing this?