Wednesday, 12 April 2017

How to send response using twice or more callback in one request

I'm using express and the request POST look like that

router.post('/', function(req, res, next){
 var data = req.body;
 getRandom(data, function(value){
     res.json({value: value});
 });
});

POST is sent through ajax and then update textarea with new data.

 $.ajax({
           type: "POST",
           url: "/",
           data: JSON.stringify(datareq),
           dataType: 'json',
           contentType: 'application/json',
           success: function(x){
               $.each(x, function(index, value) {
                  $('.textarea').append(value + '\n');
               });
           },
           error: function(x) {
                console.log(x + 'error');
          }
       });

How to send this using one POST and a few response. User received one data in textarea when cb finished and then another data and so one till the end.

<textarea>
 data 1 - 1sec
 data 2 - 2sec leater
 data 3 - 3 second later
 ...
</textarea>

I add Time (1sec ...) only to show that callback has a lot to do to send another response.

Of course this not working because res.send() close connection and I received error

So how to achieve my idea, to sending simultaneously after post request. I want to give user data very fast, then another one when is ready not waiting for all and then send response.



via cyprian

No comments:

Post a Comment