refactorization of ajax call using promises

0

I have a code that requests Ajax using callbacks, the task is to transform it into promises that are linked. So far, I do the two services using $ .when and .done the issue is that this confused about how to sort the parameters that were previously requested in the callback. Here the original code:

var PlayerService = {
  getPlayerTeamId: function(playerId, callback) {
    $.ajax({
      url: "/player/" + playerId(8) + "/team",
      success: function(team) {
      callback(team.id)
    }
  });
},
getPlayers: function(teamId, callback) {
  $.ajax({
    url: "/team/" + teamId + "/player",
    success: callback
    });
  }
};

var PlayerDetailsController = {
  playerId: 8,
  showTeammatesClick: function() {
    PlayerService.getPlayerTeamId(this.playerId, function(teamId) {
    PlayerService.getPlayers(teamId, function(playerList) {
    // Render playerList
      });
    });
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And my code:

var PlayerService = {
  
  getPlayerTeamId: function () {
       return $.ajax({
                url: "/player/" + playerId + "/team", 
                type: 'GET'
      });
  },
  getPlayers: function (data) {
      return $.ajax({
        url: "/team/" + teamId + "/player",
        type: 'GET'
      });   
  }
}

var PlayerDetailsController = {
   
    playerId: 8,
    showTeammatesClick: function() {
     document.getElementById('myButton').addEventListener('click', function () {
       //debugger;
      $.when(PlayerService.getPlayerTeamId(),PlayerService.getPlayers())
       .done(function(playerId, teamId){
            console.log('resultados',playerId, teamId);
      });
     });
    }
  }
      
PlayerDetailsController.showTeammatesClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <button id="myButton">Click</button>
</body>

Any ideas if I'm on the right track? Thanks

    
asked by MelC 06.04.2018 в 05:16
source

0 answers