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
Promise resolve() method: Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With