简体   繁体   中英

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 want to grab, parse and manually merge. The problem is I am getting stuck in promise jail. Let me show you some of the code from my angularjs controller.

$scope.tests = [];

$scope.tests = $http.get('results/testResults.json').then(function(res) {
  return res;
});

console.dir($scope.tests);

From the console.dir I am getting a promise but what I was hoping for was the data from the res variable. There has to be some way to get that data out. Is there no way to get that data out of the promise to a global variable so other promises of functions can use this data? Thanks

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM