muliku
muliku

Reputation: 476

Node.JS make multiple POST requests untill response is empty

I'm making a POST request to API that has limited number of characters in response. In order to get full response I need to make multiple POST requests and then append them all to one file. I'm not that familiar with asynchronous programming so I can't think of a solution for my problem. Here is snippet of my code:

var request = require('request');
var fs = require('fs');

var options = {//options for POST request body};

request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
       fs.appendFileSync("./response.json", JSON.stringify(body), 'utf8');
       var resp = JSON.parse(fs.readFileSync('./response.json', 'utf8'));
       options.offset = resp.parameters.length; //this is length of my data so far, next request will have this number in it and response will be new data offseted by this number
    }
});

And after this request I need to make another one untill body.length is zero. So I guess what I need is to call request function from its own callback. How do I achieve this? Thanks!

Upvotes: 0

Views: 45

Answers (1)

Jemi Salo
Jemi Salo

Reputation: 3751

Like JM-AGMS said, wrap the request function call in another function to have the callback of one request trigger the next request.

A recursive solution would look somewhat like this:

var request = require('request');
var fs = require('fs');

var options = {/*options for POST request body*/};

function loop(options) {
  request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      if (body.length !== 0) {
        fs.appendFileSync("./response.json", JSON.stringify(body), 'utf8');
        var resp = JSON.parse(fs.readFileSync('./response.json', 'utf8'));
        loop({ ...options, offset: resp.parameters.length });
      }
    }
  });
}

Upvotes: 1

Related Questions