Is there any way to fix this?

I have a file named always.js and index.js.

index.js:
var always = require("./always.js");

function f() {
always();
console.log(“this should not be printed”);
}
f();

always.js:
module.exports = func;

function func() {
console.log(“ok”);
return;
}

Is there any way to stop the f() function from the func() function?

Yeah, I think you’re referring to exceptions. I probably wouldn’t be the best person to explain it, but there’s good reference online about it.

You can use something called coroutines. Coroutines are basically threads, but they don’t run in parallel, they run when they are given a certain signal and stops when they yield. To use coroutines in javascript you must create something called generator functions. That way you can stop execution midcode and resume when you need to again. Note that this might have implications when running async functions.

Here is a good read about generator functions.

3 Likes

Now that’s very useful! :+1:

There’s several ways to approach this, which works best depends on more context than is given in the question.

Example with exception:

try {
  always();
  console.log("wont run this");
}
catch(e) {
  console.error(e); // or could ignore the error
}

always.js …

throw "custom error";


Example with returning a value:

  if (always()) {
      console.log("wont run this");
  }

always.js …

return false;

2 Likes