I am relatively new to nodejs. I've been recently pooling all of the collective knowledge i've gathered through the past couple of months into an project. I believe I've ran into my first "blocking" issue in nodejs.
I have a page that loads two request()
calls they are async and nested accordingly. The innermost one uses data from the innermost to redirect the user.
request(parameters,function(error, response, data){
//the first request passes a token
request(newParamters,function(error, response, data){
//the second request passes a url
res.redirect(data.info.url);
});
});
The error is that when I open this up in many browser tabs it ends up breaking after the first couple then the server says data.info.url
is undefined.
My question to you is: Should I only be performing one request at a time? I could save the token from the first request()
and redirect the user to the second request()
would this help? I've been very conscience about async and not blocking and I'm shocked that this is happening. Any feedback would be great!
Nesting like this is going to lead to many problems.
I prefer this pattern, way I break-up everything to named functions that are much easier to read.
When a function completes it calls the next and so on.
This pattern is "non-blocking", so when the first request is made the nodejs process exits and continues when the response is received only then will the second function get called.
When the second request is made the nodejs process exits again. The redirect will only occur after the response is received.