Tuesday 12 April 2016

stupid question, but I couldn't find an answer...how should you handle "multi-threaded"ness in Node

I know most are going to say async-call backs, but I'm looking for a more specific scenario which im not sure if it will work.So here is my understanding in JS/Node/Express.Since JS is a single-threaded application, we are to avoid blocking logicfor(i = 0; i < 1 MILLION; i++) would probably be frowned upon.Suppose our Express API looks something like this:api.(/getusers, function(req,res) { //make some async db call, 5 secs users = db.get(); //sort users, takes 10 secs for(i = 0; i < users.length; i++) //do some other non-trivial things 3 secs //make dinner? 2 secs return users at some point?; } And we have the scenario, where 2 users (A/B) call /getusers seconds from each other.my understanding with JS, is that A will wait 20 secs for his response, and user B will wait (20 , for A to be done) + 20 for his response.coming from a Java background, the above would be some what easy. just multi-thread the function blocks so that the 1M user for loop wont block your whole app. and A/B would be able to get their data independent of each other.but how would you handle large for loops and what not in JS/Express apps?How does a callback save the day in this hypothetical scenario?

Submitted April 13, 2016 at 03:36AM by T-rex_with_a_gun

No comments:

Post a Comment