我有一组执行某些任务的.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);
});
发布于 2019-03-20 08:53:10
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的实现细节,因此除非其他更安全的解决方案对您不起作用,否则不应使用。
https://stackoverflow.com/questions/55251874
复制相似问题