user6605213
user6605213

Reputation:

How to sequentially execute http get in node

function getStuff(serial){
    return new Promise(function (fulfill, reject){
      request("url using serial", function (error, response, body){
        try {
          fulfill(body);
        } catch (error) {
          reject(error);
        }
      }, reject);
    });
}

while(FLAG) {
  var p = getStuff(x);
  p.then(function(obj){
    console.log(obj)
    if(some condition on obj) FLAG = false
  })
  //WAIT HERE TILL ITS DONE!!!!
}

How do I use this promise to sequentially execute a series of calls with different serial using a loop?

Upvotes: 0

Views: 883

Answers (2)

aaronjkrause
aaronjkrause

Reputation: 849

The short answer is you don't. Anything you want to do with the data coming back from a call like that has to be in the callback. So:

var x = 1
function trial() {
  http.get("endpoint url", function (response) {
    x++;
    list.push(response.data);
    console.log(x) // 2
  });

  return x;
}
console.log(trial())// 1

The call you're dispatching is asynchronous. At the moment there isn't anything in the spec that lets us wait for the results of a call. All synchronous code (everything you have outside the function) will execute before the results of the call comes back no matter how long it takes. So you have to handle the data inside the callback or something else that manages async like promises.

Upvotes: 0

Rho
Rho

Reputation: 380

With node you need to structure your code for asynchronous calls.

kkreft's comment describes some tools you can use to help with this.

An implementation of your code that could work would be:

var x = 1
var list = []
function trial(callback) {

  http.get("endpoint url", function (err, response) {
        x++;
        list.append(response.data);

        if (err) 
           callback(err);
        else
           callback(null, x);
    });
}

trial(function(err, r) {
     console.log(r);
     console.log(list);
});

Upvotes: 1

Related Questions