简体   繁体   中英

How to write async code in my project

Could you please provide an example which makes this code asynchronous 1)i have to read file by $http.get function from the server 2) read the file to an array 3)process it (reBuild it) 4) and show progress bar on every action

so the code is :

$http.get(filename).success(function (data) {
     words = data.split(/\n| /);
     reBuild(words) //this action takes at least 5 seconds
     Process(words) // this action takes at least 4 seconds
})

and i want to make it asynchronous, i dont want to freeze my thread when reBuild and Process have been excuted Any idea how to do this?

您可以处理事件,但是最简单的方法是使用setTimeout并分批处理长循环。

Assuming that 'reBuild' has to finish before 'Process' can run, the best way to approach it IMO is to make reBuild and Process functions return promises instead. Promises are a javascript way of dealing with async events - http://docs.angularjs.org/api/ng .$q .

For example, for your reBuild method instead of having something like this:

var reBuild = function(words) {
  // 5 second operation here
  return words;
}

Do it like this: (You'll need to inject the $q and $timeout services into your controller to make it work)

var reBuild = function(words) {
   var deferred = $q.defer();

   $timeout(function() {
       // do 5 second operation
       deferred.resolve(words);
   });

   return deferred.promise;
}

And then in your controller you can do:

$http.get(filename).success(function (data) {
     words = data.split(/\n| /);
     reBuild(words).then(function(reBuiltWords) {
         Process(reBuiltWords);
     }); 
})

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