1

Understand that NodeJS is a single thread process, but if I have to run a long process database process, do I need to start a web worker to do that? For example, in a sails JS app, I can call database to create record, but if the database call take times to finish, it will block other user from access the database.

Below are a sample code i tried

var test = function(cb) {
                for(i=0;i<10000;i++) {
                    Company.create({companyName:'Walter Jr'+i}).exec(cb);
                }
            }
            test(function(err,result){

            });
            console.log("return to client");
            return res.view('cargo/view',{
                model:result
            });

On first request, I see the return almost instant. But if I request it again, I will need to wait for all the records being entered before It will return me the view again.

What is the common practice for this kinda of blocking issue?

1 Answer 1

3

Node.js has non-blocking, asynchronous IO.

read the article below it will help you to restructure your code http://hueniverse.com/2011/06/29/the-style-of-non-blocking/

Also start using Promises to help you avoid writing blocking IO.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for the link. But I have already read that before I post here. I think it's my database query blocking the code, as it has no issue when accessing other part of the application that don't need db connection while the query is still running
what you need to do is use Promises and return the Promise in the test function, so your function will return the promise right away, and within the promise you can start writing to the DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.