I have FuncA who call FuncB .I want FuncA to continue processing without waiting FuncB to be finished. Is this possible in javascript ?
Thank you .
CodePudding user response:
JavaScript operates on a single event loop. This means it can, generally, only do one thing at a time.
Asynchronous operations in JavaScript (which usually involve code written in languages other than JavaScript) happen outside the main event loop which, when finished, put a callback function in a queue to be run when the event loop stops being busy.
Judging from your comments (please read How to Ask and provide a Minimal, Reproducible Example in future), FuncB
is a long-running JavaScript function that blocks the main event loop. Nothing in pure JavaScript can avoid it blocking.
Some JavaScript implementations allow you to move that logic outside the main event loop so it runs elsewhere and doesn't block.
For example, if you are using Node.js you could use worker threads to run some JS outside the main event loop. You can go a step further and use node-gyp to rewrite your long-running code in C (which might be more performant).
If, on the other hand, you were writing code to run in a webpage, you could use Web Workers.
If you are running your JS in some other environment (such as a Photoshop plugin, or on Windows Scripting Host) then you'd need to look for an alternative for that environment (and you might find yourself entirely out of luck).
CodePudding user response:
There are multiple ways of doing that, basically launching an asynchronous task, for example in the code:
function FuncB() {
console.log("FuncB started");
for (var t = 0; t < 100; t ) {
console.log("value of t funcB" t);
}
}
function FuncA() {
console.log('calling');
FuncB();
console.log("FuncA loading ...")
for (var t = 0; t < 100; t ) {
console.log("value of t" t);
}
}
...launch the FuncB()
inside FuncA()
with one on these:
setImmediate(() => FuncB());
setTimeout(() => FuncB());
Promise.resolve().then(() => FuncB());
..or if you are in NodeJS you can use too:
process.nextTick(() => FuncB());