Run NodeJS event loop / wait for child process to finish

前端 未结 4 1031
暖寄归人
暖寄归人 2021-02-04 11:01

I first tried a general description of the problem, then some more detail why the usual approaches don\'t work. If you would like to read these abstracted explanations go on

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 11:31

    The rule of asynchronous programming is, once you've entered asynchronous code, you must continue to use asynchronous code. While you can continue to call the function over and over via setImmediate or something of the sort, you still have the issue that you're trying to return from an asynchronous process.

    Without knowing more about your program, I can't tell you exactly how you should structure it, but by and large the way to "return" data from a process that involves asynchronous code is to pass in a callback; perhaps this will put you on the right track:

    function getImportantData(callback) {
        importantDataCalculator = fork("./runtime");
        importantDataCalculator.on("message", function (msg) {
            if (msg.type === "result") {
                callback(null, msg.data);
            } else if (msg.type === "error") {
                callback(new Error("Data could not be generated."));
            } else {
                callback(new Error("Unknown message from sourceMapGenerator!"));
            }
        });
    }
    

    You would then use this function like this:

    getImportantData(function(error, data) {
        if (error) {
            // handle the error somehow
        } else {
            // `data` is the data from the forked process
        }
    });
    

    I talk about this in a bit more detail in one of my screencasts, Thinking Asynchronously.

提交回复
热议问题