0

I have a function that creates an object based on db data, and some web_based json.

function makeObject(dbdata){

   var obj = {};
   obj.id = dbdata.id;
   obj.url = dbdata.url;

   request(dbdata.url,function(err,res,body){
      obj.inventory = JSON.parse(body).inventory;
   });

   return obj
}

This obviously doesn't fill in the inventory property (async, etc...) nor does it work with the return inside request. I know the answer is pretty basic, but I just can't see it. help,please!

xShirase
  • 11,975
  • 4
  • 53
  • 85

1 Answers1

1

You can either pass in a callback argument or return a promise. request has to return a promise or you have to promisify it in some way. The callback solution is easier to get going as it stands.

function makeObject(dbdata, cb) {
    /* your codes */
    request(args, function (err, res, body) {
        obj.inventory = JSON.parse(body).inventory;
        cb(err, obj);
    });
}

Then you would use it like so

makeObject(dbdata, function (err, obj) {
    // handle err

    // do things with obj
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405