如何在Node js中以同步的方式单独处理.js文件后,每个人都完成了任务



我有一组执行某些任务的.js文件。id喜欢在每个人完成任务后以同步方式分别处理此文件。

现在,当我运行代码时,所有函数都以异步的方式执行完美。恐怕我还尝试过承诺(查看//代码中的//文件父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);
});

requiremodule.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允许您通过将该功能传递给它同步运行承诺。

示例:

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的实现详细信息,除非其他更安全的解决方案不适合您。

最新更新