How to create a AngularJS promise from a callback-based API

╄→гoц情女王★ 提交于 2019-12-17 10:04:13

问题


wifiservice.js:

angular.module('app.WifiServices', [])
    .factory('WifiService', function(){
        var unique_array = angular.fromJson('[]');

        function win_wifi(e){
        alert("Success");
        }

        function fail_wifi(e){
        alert("Error");
        }

        function connectWifi(wifi_ssid){
          WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
        }

        function listHandler(a){

      var network_array = [];
      for(var i=0; i<a.length; i++){
        network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
      }

      unique_array = network_array.filter(function(elem, pos) {
        return network_array.indexOf(elem) == pos;
      });

      // alert("Wifi List Ready!");
    }

    function getScanResult(){
      WifiWizard.getScanResults(listHandler, failNetwork);
    }

    function successNetwork(e){
      window.setTimeout(function(){
        getScanResult();
      }, 3000);
    }

    function failNetwork(e){
      alert("Network Failure: " + e);
    }

    window.setTimeout(function(){
      WifiWizard.startScan(successNetwork, failNetwork);
    }, 1000);

        return {
          list: function(){
            return unique_array;
          },

          connectionToWifi: function(name){
            connectWifi(name);
          }
        };
    });

My whole controller:

app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {

 $scope.wifiList = [];

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  $scope.$apply();
 }, 5000);

 $scope.getList = function() {
  $scope.wifiList = WifiService.list();
  return $scope.wifiList;
 }

 $scope.connectWifi = function(name) {
  WifiService.connectionToWifi(name);
 }

 $scope.checkin = function() {
  $scope.getList()
  .then(function(result) {
     console.log(result);
 });
}

}]);

What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.

Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?


回答1:


How to create a AngularJS promise from a callback-based API

To create an AngularJS promise from a callback-based API such as WifiWizard.connectNetwork, use $q.defer:

function connectWifi(wifi_ssid) {
   var future = $q.defer();
   var win_wifi = future.resolve;
   var fail_wifi = future.reject;
   WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
   return future.promise;       
};

The above example returns a $q Service promise that either resolves or rejects using the callbacks from the API.




回答2:


Well, I came up with something different:

var unique_array = [];
  $scope.wifiList = [];
  $ionicLoading.show({
    template: "Scanning surrounding AP's..."
  });

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  while ($scope.wifiList == []) {
    console.log('Scanning...');
  }
  $scope.$apply();
  $ionicLoading.hide();
 }, 5000);

What I realize is that the scanning starts once I load the view. So, I added an IonicLoader to force the user to wait, and not be able to press any buttons till the scan is finished. So no function shall wait one another. Not quite code-wise correct, but it does what I need.



来源:https://stackoverflow.com/questions/43121872/how-to-create-a-angularjs-promise-from-a-callback-based-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!