javascript - 仅在另一个脚本完成后才运行一个脚本的方法有哪些?

标签 javascript node.js asynchronous promise callback

可以说这是我的代码(只是我为展示想法而编写的示例)

var extract = require("./postextract.js");
var rescore = require("./standardaddress.js");

RunFunc();

function RunFunc() {
    extract.Start();
    console.log("Extraction complete");
    rescore.Start();
    console.log("Scoring complete");
}

我不想让 rescore.Start() 运行,直到整个 extract.Start() 完成。这两个脚本内部都包含函数的蜘蛛网,因此将回调直接放入 Start() 函数似乎不可行,因为最终函数不会返回它,而且我在理解如何使用 Promises 方面遇到了很多麻烦。我可以采取哪些方法来实现这一目标?

这些是 extract.Start() 开始和结束的脚本。 OpenWriter() 是通过多个其他函数和流获取的,实际的 fileWrite.write() 位于附加到此的另一个脚本中(尽管不需要检测运行结束。目前, fileWrite.on('finish')是我希望脚本被确定为完成的地方

module.exports = {
  Start: function CodeFileRead() {
    //this.country = countryIn;
    //Read stream of thate address components
    fs.createReadStream("Reference\\" + postValid.country + " ADDRESS REF DATA.csv")
      //Change separator based on file
      .pipe(csv({escape: null, headers: false, separator: delim}))
      //Indicate start of reading
      .on('resume', (data) => console.log("Reading complete postal code file..."))
      //Processes lines of data into storage array for comparison
      .on('data', (data) => {
        postValid.addProper[data[1]] = JSON.stringify(Object.values(data)).replace(/"/g, '').split(',').join('*');
        })
      //End of reading file
      .on('end', () => {
        postValid.complete = true;
        console.log("Done reading");
        //Launch main script, delayed to here in order to not read ahead of this stream
        ThisFunc();
      });
  },

  extractDone
}

function OpenWriter() {
    //File stream for writing the processed chunks into a new file
    fileWrite = fs.createWriteStream("Processed\\" + fileName.split('.')[0] + "_processed." + fileName.split('.')[1]);
    fileWrite.on('open', () => console.log("File write is open"));
    fileWrite.on('finish', () => {
      console.log("File write is closed");
    });
}

编辑:我不想简单地将下一个脚本添加到前一个脚本的末尾并放弃主文件,因为我不知道它会持续多长时间,并且它应该被设计为能够持续超出我们开发期的其他脚本。我不能直接使用现有的软件包,因为公司的审批时间长达两周,而我需要立即完成此操作

双重编辑:这是我的所有代码,每个脚本和函数都是我编写的,因此我可以使被调用的脚本执行所需的操作

最佳答案

您可以将函数包装在 Promise 中并返回它。

module.exports = {
  Start: function CodeFileRead() {
    return new Promise((resolve, reject) => {
      fs.createReadStream(
        'Reference\\' + postValid.country + ' ADDRESS REF DATA.csv'
      )
      // .......some code...
      .on('end', () => {
        postValid.complete = true;
        console.log('Done reading');
        resolve('success');
      });
    });
  }
};

并像这样运行 RunFunc:

async function RunFunc() {
  await extract.Start();
  console.log("Extraction complete");
  await rescore.Start();
  console.log("Scoring complete");
}

//or IIFE
RunFunc().then(()=>{
  console.log("All Complete");
})

注意:当发生某些错误时,您也可以/应该通过 reject("some error") 来处理错误。

了解 TheFunc() 后进行编辑:

制作一个新的事件发射器可能是最简单的解决方案:
eventEmitter.js

const EventEmitter = require('events').EventEmitter
module.exports = new EventEmitter()
const eventEmitter = require('./eventEmitter');
module.exports = {
  Start: function CodeFileRead() {
    return new Promise((resolve, reject) => {
      //after all of your code
      eventEmitter.once('WORK_DONE', ()=>{
        resolve("Done");
      })
    });
  }
};
function OpenWriter() {
  ...
  fileWrite.on('finish', () => {
    console.log("File write is closed");
    eventEmitter.emit("WORK_DONE");
  });
}

像以前一样运行 RunFunc。

关于javascript - 仅在另一个脚本完成后才运行一个脚本的方法有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61550726/

相关文章:

node.js - 在 Node.js 中将内部服务器错误消息转换为客户端可读消息的最佳实践有哪些?

asynchronous - 如何在 flutter 应用程序中显示 5 分钟不可停止的计时器?

javascript - 100 个或更多内部 javascript 文件优化?

javascript - 为什么在我的 JS 嵌套数组中得到 "arr[i] is undefined"?

javascript - Ajax 调用成功后 JQuery 调用不工作

javascript - 替代 CSS3 变换 : rotate(xdeg) in CSS2 or Javascript to rotate text

javascript - 数据未存储在 Mongodb 中

javascript - 在 hapi.js 中,身份验证方案和策略有什么区别?

javascript - 如何异步删除类函数?

spring - 使用 Spring Servet 为 REST API 处理创建异步线程