Json after successful return undefined

I am using JS with Angular, I ran into the following problem.

I get the data from the requestService, so I call the request function and then do something with the data in the "success" function. Everything is fine inside this function, and I get all my results, but as soon as I get away from the success function, my results are undefined. I read some other questions / answers about similar issues and tried other things. However, I really don't know how to pass this, and I would like to ask this explicitly with a code example:

function loadShips() {
      var count = 0;
      RequestService.getShips(nelat, swlat, nelong, swlong, timestamp)
      .success(function(results) {
        var groupedShips = results.aisData.aisGroupedByShipType;
        _.each(groupedShips, function(groupedShip) {
          _.each(groupedShip, function(ship) {
            Markers['marker' + count] = createMarker(ship);
            count++;
          });
        });
        console.log(Markers, '#1')
        return Markers
      });
      console.log(Markers, '#2');
      return Markers;
    } 

So, can someone tell me why the markers on the printout from "# 1" are defined, and in "# 2" they are undefined.

+4
source share
2

, , # 2 success. , .

factory , . :

function loadShips(callBack) {
    var count = 0;
    RequestService.getShips(nelat, swlat, nelong, swlong, timestamp)
        .success(function(results) {
            var groupedShips = results.aisData.aisGroupedByShipType;
            _.each(groupedShips, function(groupedShip) {
                _.each(groupedShip, function(ship) {
                    Markers['marker' + count] = createMarker(ship);
                    count++;
                });
            });
        console.log(Markers, "#1");
        callBack(Markers);
    });
} 

:

function myCallback(markers){
    console.log(markers, "#2");
    //assign markers to something
}

loadShips(myCallback);
+3

P, , .

, , loadShips, ajax wonderland, .

, , - , , , . , , , , .

function loadShips() {
    var count = 0;
    RequestService.getShips(nelat, swlat, nelong, swlong, timestamp)
    .success(function(results) {
      var groupedShips = results.aisData.aisGroupedByShipType;
      _.each(groupedShips, function(groupedShip) {
        _.each(groupedShip, function(ship) {
          Markers['marker' + count] = createMarker(ship);
          count++;
        });
      });
      doFancyWonderfulThingsInTheOcean(Markers);
    });
 } 
+1

Source: https://habr.com/ru/post/1626438/


All Articles