[英]How to process .JS files individually in a synchronously fashion one by one in node js after each one of them have finished their tasks?
我有一组执行某些任务的.js文件。 我喜欢在每个文件完成任务后以同步方式单独处理这些文件。
现在,当我运行我的代码时,所有函数都以完全异常的方式执行。 我担心我也尝试过promises(看看代码中的FILE parent v2)但是似乎仍然按顺序执行的任务还没有等待一个接一个地处理。
我很确定必须有一个基本的解决方案来解决这个问题。 但我的编程技巧很少。
感谢您的理解。
现在我的代码看起来像这样:
//FILE parent.js const cp = require('child_process'); const path = require('path'); //PROCESS1 var child_call = cp.fork("process1.js") child_call.on("exit", () => { console.log("1st funtion finished"); }) //PROCESS2 var child_capture = cp.fork("process2.js") child_capture.on("exit", () => { console.log("2nd funtion finished"); }) //PROCESS3 var child_render = cp.fork("process3.js") child_render.on("exit", () => { console.log("3rd funtion finished"); }) //FILE v2 Promisess parent.js const async = require('async'); const cp = require('child_process'); const path = require('path'); function addPromise() { return new Promise(resolve => { var child_call = cp.fork("process1.js") child_call.on("exit", () => { console.log("1st funtion finished"); }) resolve() }); } function addCapture() { return new Promise(resolve => { var child_capture = cp.fork("process2.js") child_capture.on("exit", () => { console.log("2nd funtion finished"); }) resolve() }); } function addRender() { return new Promise(resolve => { var child_render = cp.fork("process3.js") child_render.on("exit", () => { console.log("3rd funtion finished"); }) resolve() }); } async function addAsync() { const a = await addPromise(); const b = await addCapture(); const c = await addRender(); return a + b + c; } addAsync().then((sum) => { console.log(sum); });
require
和module.exports
立即跳出的一个解决方案是使用require
而不是使用child_process.fork
。 这样导入的代码将同步运行,您将获得返回的直接输出。
例:
function add() {
const a = require('a.js');
const b = require('b.js');
const c = require('c.js');
return a + b + c;
}
// or you can make it more usable
function addModules(...fileNames) {
return fileNames
.map(fileName => require(fileName))
.reduce((total, x) => total + x, 0);
}
请注意,如果您希望使用这些文件,则需要从这些文件中导出结果 。
// Do your stuff here:
const x = 42;
// Export it
module.exports = x;
deasync
Deasync允许您通过将该函数传递给它来同步运行promise。
例:
const cp = require('child_process');
const deasync = require('deasync');
const fork = deasync(cp.fork);
function addPromise() {
const child_call = fork('process1.js');
// now synchronous
};
// repeat as needed
function add() {
const a = addPromise();
// ...
return a + b + c;
}
注意: deasync
在语言级别公开Node.js的实现细节,因此除非其他更安全的解决方案不适合您,否则不应使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.