0

How can I assign value to an array from an async function and use it outside the scope of said function?

Basically I have a factory that randomizes values in an array, so I can attach images randomly to divs.

$scope.Resources = ResourceFetch.getResource().then(function(resources){
    $scope.img1 = JSON.stringify(resources.img1);
    $scope.img2 = JSON.stringify(resources.img2);
    $scope.img3 = JSON.stringify(resources.img3);
    $scope.img4 = JSON.stringify(resources.img4);

    var myArray = [$scope.img1, $scope.img2, $scope.img3, $scope.img4];
    console.log('myArray is ' + myArray); // <- Fine.

    var shuffledArray = [];

    ShuffleArray.getShuffled(myArray).then(function(array){
        shuffledArray = array;
        console.log('Shuffled array is ' + array); // <- Fine.
        console.log('Shuffled array again ' + shuffledArray); // <- Fine
        });

   console.log('Shuffled array outside is  ' + shuffledArray); // <- Nothing.
});
angularchobo
  • 183
  • 1
  • 3
  • 17

1 Answers1

0

your code looks fine, but don't forget that getShuffled is probably async and finishes only AFTER

console.log('Shuffled array outside is  ' + shuffledArray); // <- Nothing.

is called.

sagie
  • 1,744
  • 14
  • 15
  • That is exactly my problem. So let's say I use `$scope.shuffledImg1 = array[0]` inside the function and use the expression in my view - it works fine. But how can I use the array outside of the async function scope? – angularchobo Aug 31 '16 at 13:33
  • I dont know how you are using the value but your js is fine. If you must have it sync, than implement a sync shuffle but again dont know if you need to because i dont know how youbare using the data – sagie Aug 31 '16 at 13:36