programing

약속을 기다리는 거야?

golfzon 2023. 3. 20. 23:48
반응형

약속을 기다리는 거야?

다음과 같은 angularjs 코드가 있습니다.

$scope.clients = commonFactory.getData(clientFactory.getClients());
if ($scope.clients.length > 0) {
    $scope.sampleForm.ClientId = $scope.clients[0].ClientId;
}

또한 commonFactory의 getData 함수:

factory.getData = function (method) {
    method.then(function (response) {
        return response.data;
    }, function (error) {
        $rootScope.alerts.push({ type: 'error', msg: error.data.ExceptionMessage });
    });
};

문제는 비동기 호출로 인해 $scope.clients.length가 해당 회선에 도달했을 때 정의되지 않았다는 것입니다.

$scope.clients가 할당되었다는 것을 알 때까지 길이 체크를 하지 않는 방법이 있습니까?이런 걸 본 적이 있어요

$scope.clients = commonFactory.getData(clientFactory.getClients()).then(function () {
    if ($scope.clients.length > 0) {
        $scope.sampleForm.ClientId = $scope.clients[0].ClientId;
    }
});

쇠사슬을 채우는 중then약속은 했지만, 절대 안 돼...여기서의 목표는 getData 메서드를 사용하여 오류를 검출하기 위한 다수의 보일러 플레이트 코드를 회피하는 것입니다.내가 잘못 가고 있는 건 아닐까?

이것은 약속의 가장 기본적인 상황이다.당신은 단지 약속만 하면 된다.var deferred = $q.defer()비동기 조작을 시작할 때와의 약속을 해결합니다.deferred.resolve(result)비동기 조작이 완료되었을 때,deferred.promise사용할 수 있습니다.Angular의 비동기 메서드는 내부적으로 이를 수행하고 이미 약속을 반환하므로 새로운 약속을 만드는 대신 동일한 약속을 반환할 수 있습니다.$q.defer()접속할 수 있습니다..then약속을 돌려주는 어떤 것이든요또한, 에서 값을 반환하는 경우then그 가치는 약속으로 포장되기 때문에then체인은 계속할 수 있다

angular.module('myApp', [])

.factory('myService', function($q, $timeout, $http) {
  return {
    myMethod: function() {
      // return the same promise that $http.get returns
      return $http.get('some/url');
    }
  };
})

.controller('myCtrl', function($scope, myService) {
  myService.myMethod().then(function(resp) {
    $scope.result = resp.data;
  });
})

체인 접속이 조금 더 재미있습니다.

.factory('myService', function($q, $timeout, $http) {
  return {
    myMethod: function() {
      // return the same promise that $http.get returns
      return $http.get('some/url').then(function() {
        return 'abc';
      });
    }
  };
})

.controller('myCtrl', function($scope, myService) {
  myService.myMethod().then(function(result) {
    console.log(result); // 'abc'
    return someOtherAsyncFunc(); // for example, say this returns '123'
  }).then(function(result) {
    console.log(result); // '123'
  });
})

언급URL : https://stackoverflow.com/questions/18752222/waiting-for-a-promise

반응형