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.
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)
}
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With