Skip to content Skip to sidebar Skip to footer

Get Data Out Of A Promise Instead Of Returning A Promise

I am so sorry if the other promise threads have answered this but when looking at some of them I am just not getting the answer to solve my issue. I have three json files that I wa

Solution 1:

The promise completes some time in the future. You are examining the promise variable before the data is in the promise. You should stay in the promise chain to use your data. Outside the promise chain, you don't know the timing of the asynchronous events (that's why you use promises in the first place).

If you really don't want to use the data right in your first .then() handler which is the ideal place to use it, then you can chain another .then() onto your promise:

$scope.tests = $http.get('results/testResults.json');

$scope.tests.then(function(data) {
   // can use data here
});

FYI, promises do not populate data into global variables. They make the data available to use in .then() callbacks when those callbacks are called.

Solution 2:

Make up an an property and stick it on the window object, like this,

window.myProperty

Then pass your data to it, from inside the promise, like this,

window.myProperty = data;

And pick it up, when you are back outside, like this,

myVariable = window.myProperty;

Or the reverse, because I cannot seem to get data in or out of some Promises, so that would go like this,

Again, make up a property and stick it on the window object, like this,

window.myProperty

Then pass your data to it, from outside the promise, like this,

window.myProperty = data;

And pick it up, when you are inside, like this,

myVariable = window.myProperty;

This cannot be the best way to do this! Does anyone know a better way?

Post a Comment for "Get Data Out Of A Promise Instead Of Returning A Promise"