简体   繁体   中英

Return value in a synchronous function after calling asynchronous function (setinterval) within it

I am working on this function on Node.js, with the following requirements:

  1. As far as possible, maintain synchronous code flow (so that it is simple to read/follow)
  2. Able to return value, so that it can be passed up to the higher-level function.
  3. 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!

It is fundamentally impossible to "deasync" without blocking.

"Asynchronous" means that the result will be produced at some later time . "Synchronous" means that code execution will continue right now. These two simply do not go together. If a synchronous operation needs to wait for the completion of an asynchronous operation, it must suspend operation until the operation has completed; that means it'll block .

The friendliest syntax without devolving into callback hell is to use Promises. They sort of allow you to write synchronous-ish looking code while delegating the intricacies of asynchronous callbacks into the background.

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