Execute multiple tasks asynchronously and return first successful result in JavaScript function

后端 未结 3 1498
别那么骄傲
别那么骄傲 2021-01-05 16:27

I have to write a javaScript function that return some data to the caller.

In that function I have multiple ways to retrieve data i.e.,

  1. Lookup from ca
3条回答
  •  [愿得一人]
    2021-01-05 17:17

    Create a broadcast event in your api calls, then create $scope.$on to listen to those broadcast, when $on get's activated do the function that refreshes those objects.

    So in your service have a function that makes an ajax calls to your rest api. You would have 3 ajax calls. And 3 listeners. Each of them would look something like this.

    This is just sudo code, but this format is how you do it something like

     $http({
            method: "GET",
            url: url_of_api,
        }).success(function(data, *args, *kwargs){
            $rooteScope.$braodcast('success', data)
        })
    

    In your controller have a listener something like this

    $scope.$on('success', function(event, args){
     // Check the state of the other objects, have they been refreshed - you probably want to set flags to check 
      if (No Flags are Set):
          $scope.data = args // which would be the returned data adn $scope.data would be what you're trying to refresh.
    }
    

提交回复
热议问题