0

I'm using request-promise to get data from an endpoint that I have. Is it posible to 'capture' a json response in a variable to use it anywhere?

try{
    var gamer = '';//variable to capture json data
    var options = {
        uri: 'http://localhost:4000/gamers/'+gamer._id+'/find',
        json: true
    };

    RequestPromise(options)
        .then(function (data) {
            gamer = data;//capturing response 
        })
        .catch(function (err) {
            console.log("Error saving player data !");
        });
    .... do something with gamer ....
}catch(err){
    res.status(500).send({
            message: err.message || 'An error occurred generating player teams !'
    });
}

The reason that I need to do this is because actually I don't have access to the database to get that information, so my only option is to consume an API to get information through collections id's.

maudev
  • 974
  • 1
  • 14
  • 32
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Nov 27 '18 at 03:57
  • `await` the `Promise` (and try/catch doesn't do anything meaningful with async operations unless you're `await`ing) – CertainPerformance Nov 27 '18 at 03:57

1 Answers1

0

Your doing a lot of things correctly already. The issue is your gamer variable will get assigned the value you expect first when your promise resolves. There are many ways to skin this cat, but to get you started try performing whatever you want to perform on the gamer variable in .then(), like this:

try{
    var gamer = '';//variable to capture json data
    var options = {
        uri: 'http://localhost:4000/gamers/'+gamer._id+'/find',
        json: true
    };

    RequestPromise(options)
        .then(function (data) {
            gamer = data;//capturing response 
            // here is the rigth place perofrm operations on the answer, as this part of the code gets executed after promise reolves. BTW. Then you don't need variable gamer.
        })
        .catch(function (err) {
            console.log("Error saving player data !");
        });
    // here is not the right place to do something with gamer as this is executed as soon as promise is initialized, not as it resolves. This means your variable will have initial value here
}catch(err){
    res.status(500).send({
            message: err.message || 'An error occurred generating player teams !'
    });
}
mindriven
  • 143
  • 1
  • 8