MaiaVictor
MaiaVictor

Reputation: 52957

Calling a function asynchronously in node.js?

In node.js, how do you call a function so it runs in background? Something like:

work = function(){
    for (var i=0; i<1000000; ++i);
    return "world!";
};

spawn(work).then(console.log);
console.log("Hello ");

Should output what you expect.

Note: not necessarily following this pattern.

Upvotes: 0

Views: 1783

Answers (3)

Jim
Jim

Reputation: 274

Nothing in Node.JS will run "in the background". This is because JS can't multi-thread. Yet it has the ability to run code back to back, for example running 2 for loops at the same time, will cause the first for loop to iterate a set amount, then the second will iterate and they will swap processing power to make it seem as if methods can be run at the same time.

Node.JS if I am not mistaken does this with the callbacks.

"Callbacks

Callbacks are a basic idiom in node.js for asynchronous operations. When most people talk about callbacks, they mean the a function that is passed as the last parameter to an asynchronous function. The callback is then later called with any return value or error message that the function produced. For more details, see the article on callbacks"

With more example and information found here -

http://docs.nodejitsu.com/articles/getting-started/control-flow/how-to-write-asynchronous-code

Upvotes: 1

kingsisyphus
kingsisyphus

Reputation: 146

Try looking at the child_process features.

I'm currently using child_process to fork processes and parallelize operations. The best part is that (unlike working in C or C++), node does a lot of the painful work for you.

Even more (a side note), you can pass JavaScript code back and forth between processes and build a powerful multi-CPU, multi-host and multi-process application for compute-intensive tasks. Don't let the negative voices tell you otherwise...node is great and it can do what you appear to be asking.

Check out http://nodejs.org/api/child_process.html

Upvotes: 0

MobileGuy
MobileGuy

Reputation: 1252

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript https://npmjs.org/package/async

Upvotes: 0

Related Questions