Chaining of asynchronous requests

1

I need to do asynchronous serial data processing (sending data to a REST server), and only at the end of all requests do I need to perform another function.

How can I control this flow if each request is asynchronous?

What I need is something like this:

for (var i=0; l<objetos.length; i++){
  var o=objetos[i];
  Enviar($q, o).then(function(){})
}
//ao término de todas as requisições acima, disparar um novo evento...
    
asked by anonymous 03.09.2015 / 18:45

2 answers

4

I think the right thing is to start a request only when another one finishes:

var enviarArquivo = function(indice)
{
    Enviar($q, objetos[indice]).then(function()
    {
        if (++indice < objetos.length)
        {
            enviarArquivo(indice);
        }
        else
        {
            // Processo finalizado
        }
    })
}

// Chamada inicial
enviarArquivo(0);

That way one request does not start without the other completing and you can tell when the last one is over.

    
03.09.2015 / 19:14
4

You can use $ q.all to wait for all the promise

var promises = objetos.map(function (o) {
    return Enviar($q, o);
});

$q.all(promises).then(function(){});

reminding you that .then () returns a new promise, in this case you can perform an action at the end of each file upload and an action at the end of the upload of all the files.

var promises = objetos.map(function (o) {
    var promise = Enviar($q, o);
    return promise.then(function(){});
});

$q.all(promises).then(function(){});
    
03.09.2015 / 20:16