Chaining of asynchronous requests

Asked

Viewed 768 times

1

I need to do the asynchronous processing of data series (sending data to a REST server) and, only at the end of all requests, 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...
  • If you have all the data on objetos, why not send them at once? Don’t overload your page with multiple requests. It’s not good practice.

  • If it is ajax there is a configuration called: async, put the async value: false, and then yes you have several functions in case of success and fail.

  • @Dontvotemedown I am sending a file and the server only accepts one file at a time.

  • @Wilson is sending the file with the cordovaFileTransfer.upload()

  • @Wilson- It is better to avoid this at all costs, not only by crashing the user interface, but also because will no longer be supported by browsers.

2 answers

4


I think it would be right to start a request only when another one is finished:

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 has finished and you can know when the last one is over.

  • 1

    Just didn’t get more perfect because the if condition should be if (++indice < (objetos.length)) ;). Thank you!

  • Intelligent solution, +1

  • @Nilsonuehara ok, thanks for the correction. I did it in my head, I thought I was right.

4

you can use the $q. all to wait for all the

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

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

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

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

$q.all(promises).then(function(){});
  • If it’s really angular, it’s the best solution.

  • Ah, I take it back. It sounds like he really needs it chain the requisitions, and this method does not guarantee this.

  • The @Dontvotemedown response solves my problem as well as assuring me the correct chaining. Anyway, your solution will also be very useful to me, so I have already given you a positive vote. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.