Get data out of a promise instead of returning a promise

后端 未结 2 2028
别那么骄傲
别那么骄傲 2021-02-05 14:49

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

相关标签:
2条回答
  • 2021-02-05 15:37

    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?

    0 讨论(0)
  • 2021-02-05 15:39

    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.

    0 讨论(0)
提交回复
热议问题