I am working on this function on Node.js, with the following requirements:
- As far as possible, maintain synchronous code flow (so that it is simple to read/follow)
- Able to return value, so that it can be passed up to the higher-level function.
- If asynchronous function has to be used, there has to be some way to "block" the flow between the asynchronous function and return statement, while at the same time not blocking the program and GUI.
Here is my code:
main.js
var some = require("./some.js");
main_fn = function () {
var result = some.some_fn();
if (result == "good") // do something
};
main_fn();
some.js
exports.some_fn = function () {
var result;
var someInterval = setInterval(function () {
// output to GUI
if (condition1) {
clearInterval(someInterval);
result = "good";
} else if (condition2) {
clearInterval(someInterval);
result = "bad";
}
// else continue with interval
}, 250);
// previous way: deasync
// it will not block event loop, however it will block the GUI ("freeze" the browser)
// require("deasync").loopWhile(function () { return result === undefined; });
// result will be undefined here if no code to "block" in between
// but I need result to be either "good" or "bad"
return result;
};
As you can see from the code, I had tried deasync (https://github.com/abbr/deasync). However, that will block the GUI. Are there any Node.js modules/workaround, something like deasync, that allow me to maintain this code structure (as far as possible) and meet my requirements on top?
It will be even better to find a solution without using native Node.js modules (modules which use C/C++ code, like deasync), as I may need to browserify the program in the future. However, I am fine with hearing any solutions from you. Thanks!