Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS - wait for full response

Tags:

php

node.js

nginx

So I have an API (written in PHP over Nginx). I use Node JS in order to send requests to that API. Sometimes it takes 5-7 seconds until the API finishes what it needs to do.

The problem is that Node JS doesn't wait for the full response to arrive.

http.get(url, function(response){
    // called right away instead of waiting until it finishes
});

I already tried using the .end() & .close() events - no luck. How can I make NodeJS to wait? or...how do I make PHP to notify node "hey, now I've finished". Thanks.

One important thing: when I try to CURL to the API, it does wait for the full response.

like image 272
Matan Reuven Avatar asked Aug 12 '26 00:08

Matan Reuven


2 Answers

When using the native http client you will have to manually append the chunks before parsing the data. For this reason, most people do not use the native http client. You want to use something like the request module.

npm install request

Followed by

var request = require('request');
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body)
  }
})
like image 200
Yuri Zarubin Avatar answered Aug 13 '26 13:08

Yuri Zarubin


NodeJS works in a fully asynchronous manner. This means that all code is executed, top-to-bottom, without waiting for any functions with callbacks.

Coming from PHP, you're expecting it to do:

ExecuteThis();
ThenThis();
AndFinallyThis();

But NodeJS doesn't do that. It'll just start executing everything at once and then return the result. Which is like running this command:

php ExecuteThis.php && php ThenThis.php && php AndFinallyThis.php

What you want is an asynchronous waterfall, a callback, a Promise, or a structure of that sort, coupled with a HTTP request.

like image 33
Adam Link Avatar answered Aug 13 '26 13:08

Adam Link



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!