简体   繁体   中英

angularjs strange array behaviour, probably related to asynchronous execution?

Difficult to reproduce, so I will try to explain instead.

Within a factory of angularjs I have a function like this

angular.module('my').factory('Database', ['$window', 'Raw', function($window, Raw) {
    return {
        read: function() {

where Raw is another factory defined below that returns a data string

Then I do this:

var lines = [];
lines = Raw.data.split("*");

which gives me an array of strings.

The strange behaviour is that it gives an error as lines[0] is undefined. I can solve this error by adding an alert

var lines = [];
lines = Raw.data.split("*");
alert(lines[0])

which shows me the expected string. But it does not work if I put a console.log command instead.

So, what's going on??

Cheers,

Sounds like you get Raw.data by async way and when you try split it, it still undefined .

If Raw.data returns promise, use then() callback than, something like:

var myModule = angular.module('myModule', []);

myModule.controller('myController', ['$scope', 'Database', function($scope, Database) {
   $scope.text =  Database.read();    
}]);

myModule.factory('Database', ['$window', 'Raw', '$q', function($window, Raw, $q) {

  return {
 read: function() {
         var deferred=$q.defer();
        Raw.data().then(function(data) {
            lines = data.split("*");
          deferred.resolve(lines); 
        });
        return deferred.promise;
     }
   }    
}]);

myModule.factory('Raw', ['$window', '$q', function($window, $q) {
    return {
        data: function() {
            var data = "blah * blah";
            var deferred = $q.defer();              
                deferred.resolve(data);               
                return deferred.promise;
        }
    }
}]);

Demo Fiddle

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