1

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?

Moshe
  • 2,583
  • 4
  • 27
  • 70
  • 1
    If you already chose to use `request-promise`, why don't you `return` the promise? – Bergi Jun 15 '17 at 19:56
  • I'm a little bit confused with async and promises, how they work, why these terms overlap. Can you explain what would returning the promise do? (I rather return the 'value' of the "body") – Moshe Jun 15 '17 at 19:57
  • You cannot return value of the body, as that will only be available in the future. That's why you have to use a callback - best within a promise. When you return a promise for the value of the body, you'd use your function as `getObjects.get(req.params.id).then(function(resp) { collection.insert(resp); res.json(resp); })` – Bergi Jun 15 '17 at 20:00
  • I see how that might work, but how do I change my get() function to behave this way? – Moshe Jun 15 '17 at 20:09
  • I think adding a `return` in front of the request-promise call should do it – Bergi Jun 15 '17 at 20:14

0 Answers0