简体   繁体   中英

Is there a way to make a blocking call in Node.Js?

It's few times harder to program using continuations (callbacks) rather than in model of straight sequential execution. Can NodeJs do blocking calls?

Yes, it can. For example you can read a file with fs.readFileSync() rather than fs.readFile(). Each library usually provides a xxxSync method for synchronous/blocking methods.

But you should NOT use the sync method very often. Remember that Node.js uses a single thread of execution for JavaScript code. If you block this thread you block it for everybody (unlike C#/Java where a new thread will be created for each request.)

If the asynch approach is too much for you you might want to use another platform (Ruby, Python, PHP).

Yes, node.js 0.11.x can do blocking calls inside if a generator. By "blocking call" I mean stopping execution of current function for a while. Look at co library.

This is the only recommended way to do blocking calls.

Other than that, you can look at fibers , but it needs to be used carefully, and not in general-purpose libraries.

There are also a couple of *Sync calls mentioned before, but please avoid using them entirely unless you're writing one-liner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM