如何从异步函数为数组赋值并在所述函数范围之外使用它?
基本上我有一个工厂随机化数组中的值,所以我可以随机附加图像到div。
$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.
});
答案 0 :(得分:0)
你的代码看起来很好,但不要忘记getShuffled可能是异步的并且仅在完成之后完成
console.log('Shuffled array outside is ' + shuffledArray); // <- Nothing.
被召唤。