Blank global array after two ajax calls

2

When doing a global variable and after doing push after two queries per ajax is left blank Can you tell me if it failed in something?

var productoT = [];
angular.module('starter', ['ionic', 'ionic.contrib.ui.tinderCards2', 'ionicLazyLoad'])
 .run(function($ionicPlatform, $rootScope, $ionicConfig, $timeout, $ionicPopup){
 }
.controller('productoGctrl', ['$scope', '$timeout', '$http','$ionicPopup', '$ionicLoading', controlfproductoG])

function controlfproductoG ($scope, $timeout, $http, $ionicPopup, $ionicLoading) {
  var typeT;

  if (localStorage.getItem('idCategoriaSelecionada')) {
    console.log(1)
    typeT = {
      actionType: 'getProductosCategoria',
      iduser: localStorage.getItem('iduser'),
      idcategotia: localStorage.getItem('idCategoriaSelecionada')
    };
  }
  else{
    console.log(0)
    typeT = {
     actionType: 'get',
     iduser: localStorage.getItem('iduser')
    };
   }

  productoUrl(
   $http,
   'ProductosService.php',
   typeT
  )
  .then(function (dato) {
    verP = dato;
    productoInfoUrl(
     $http,
     'ProductosService.php',
     dato
    )
   .then(function (det) {
     console.log(det);
     productoT.push(det);
   })
 });

 console.log(productoT);
}

function productoUrl ($http, url, dato) {
 var promise = new Promise();
 var prod, datoProducto;
 $http({
   method: 'POST',
   url: url,
   data: dato,
   headers: {'Content-Type': 'application/x-www-form-urlencoded'}
 }).success(function (res) {
    //console.log(res)
    if (res.code == '0') {
      prod = res.productos;
      promise.done(prod);
    }
    else{
     console.log(res)
    }
  });
 return promise;
}

function productoInfoUrl ($http, url, dato) {
  var promise = new Promise();
  var datoProducto;
  dato.forEach(function (dat) {
    $http({
    method: 'POST',
    url: url,
    data: {
      actionType: 'getInfo',
      idproducto: dat.id,
      tipo: dat.tipo
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (res) {
      //console.log(res)
      if (res.code == '0') {
        datoProducto = new ObjProducto(dat.id, dat.tipo, res.producto);
        promise.done(datoProducto);
      }
      else{
       console.log(res)
      }
    });
  })
  return promise;
}

function Promise () {
  this._callbacks = [];
}

Promise.prototype.then = function (callback) {
   if (typeof callback !== 'function') {
     throw new Error('[Promise.then] El argumento "callback" no es una    función ' + typeof callback);
   }
   this._callbacks.push(callback);
}

Promise.prototype.done = function () {
  var callback;
  var args = arguments;
  for (var i = 0; i < this._callbacks.length; i++) {
    callback = this._callbacks[i];
    callback.apply(null, args);
  }
}

Thank you very much for the information.

Here's how it works link

    
asked by Albert Arias 18.10.2016 в 19:09
source

1 answer

1

Already in the comments they guide you. It is because you are showing the results by console before the promises have been resolved, which are being processed asynchronously. To illustrate, try this:

productoUrl(
    $http,
    'ProductosService.php',
    typeT
)
.then(function (dato) {
    console.log('Promesa 1 resuelta');

    verP = dato;
    productoInfoUrl(
        $http,
        'ProductosService.php',
        dato
    )
    .then(function (det) {
        console.log('Promesa 2 resuelta');

        console.log(det);
        productoT.push(det);
    })
});
console.log('Tras las promesas');

The result that you will see on the console is this:

Tras las promesas
Promesa 1 resuelta
Promesa 2 resuelta

As you can see, the last line is reached before finishing executing the previous lines, which are still running asynchronously. You can use the global variable, already loaded with all the data, when the second promise is resolved, but not before:

productoUrl(
    $http,
    'ProductosService.php',
    typeT
)
.then(function (dato) { 
    verP = dato;
    productoInfoUrl(
        $http,
        'ProductosService.php',
        dato
    )
    .then(function (det) {
        console.log(det);
        productoT.push(det);
    })
   .then(function () {
     console.log(productoT);   
   }
});
    
answered by 27.10.2016 в 10:21