简体   繁体   English

只有在另一个脚本完成后才运行脚本的方法是什么?

[英]What are ways to run a script only after another script has finished?

Lets say this is my code (just a sample I wrote up to show the idea)可以说这是我的代码(只是我写的一个示例来展示这个想法)

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");
}

And I want to not let the rescore.Start() run until the entire extract.Start() has finished.而且我不想让 rescore.Start() 运行,直到整个 extract.Start() 完成。 Both scripts contain a spiderweb of functions inside of them, so having a callback put directly into the Start() function is not appearing viable as the final function won't return it, and I am having a lot of trouble understanding how to use Promises.这两个脚本都包含一个蜘蛛网的函数,因此将回调直接放入 Start() function 似乎不可行,因为最终的 function 不会返回它,而且我在理解如何使用 Promises 时遇到了很多麻烦. What are ways I can make this work?我有什么方法可以完成这项工作?

These are the scripts that extract.Start() begins and ends with.这些是 extract.Start() 开始和结束的脚本。 OpenWriter() is gotten to through multiple other functions and streams, with the actual fileWrite.write() being in another script that's attached to this (although not needed to detect the end of run. Currently, fileWrite.on('finish') is where I want the script to be determined as done 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");
    });
}

EDIT: I do not want to simply add the next script onto the end of the previous one and forego the master file, as I don't know how long it will be and its supposed to be designed to be capable of taking additional scripts past our development period.编辑:我不想简单地将下一个脚本添加到前一个脚本的末尾并放弃主文件,因为我不知道它将持续多长时间,并且它应该被设计为能够接受其他脚本过去我们的发展时期。 I cannot just use a package as it stands because approval time in the company takes up to two weeks and I need this more immediately我不能只使用 package,因为公司的审批时间最多需要两周,我更需要这个

DOUBLE EDIT: This is all my code, every script and function is all written by me, so I can make the scripts being called do what's needed双重编辑:这是我所有的代码,每个脚本和 function 都是我写的,所以我可以让被调用的脚本做需要的事情

There's no generic way to determine when everything a function call does has finished.没有通用的方法来确定 function 调用所做的一切何时完成。

It might accept a callback.它可能会接受回调。 It might return a promise.它可能会返回 promise。 It might not provide any kind of method to determine when it is done.它可能不提供任何类型的方法来确定何时完成。 It might have side effects that you could monitor by polling.它可能有副作用,您可以通过轮询来监控。

You need to read the documentation and/or source code for that particular function.您需要阅读特定 function 的文档和/或源代码。

Use async/await (promises), example:使用 async/await(承诺),例如:

 var extract = require("./postextract.js"); var rescore = require("./standardaddress.js"); RunFunc(); async function extract_start() { try { extract.Start() } catch(e){ console.log(e) } } async function rescore_start() { try { rescore.Start() } catch(e){ console.log(e) } } async function RunFunc() { await extract_start(); console.log("Extraction complete"); await rescore_start(); console.log("Scoring complete"); }

You can just wrap your function in Promise and return that.您可以将 function 包装在 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');
      });
    });
  }
};

And Run the RunFunc like this:并像这样运行 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");
})

Note: Also you can/should handle error by reject("some error") when some error occurs.注意:当发生某些错误时,您也可以/应该通过reject("some error")来处理错误。

EDIT After knowing about TheFunc():编辑了解 TheFunc() 后:

Making a new Event emitter will probably the easiest solution:制作一个新的事件发射器可能是最简单的解决方案:
eventEmitter.js 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");
  });
}

And Run the RunFunc like as before.并像以前一样运行 RunFunc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 敲除完成后运行脚本 - Run a script after knockout has finished 与动作有关的Javascript / Jquery-如何仅在另一个脚本完成后才激活命令? - Action-dependant Javascript/Jquery - how to activate a command only AFTER another script has finished? chrome扩展:页面加载javascript后运行脚本 - chrome extension: run script after page has finished loading javascript 在另一个函数内部运行函数,但仅在ajax完成之后 - Run function inside of another function, but only after ajax has finished 仅在另一个脚本完成后运行脚本 - Run a script only after another one completes 通过ajax调用多个脚本。 只有在脚本1完成执行后才应调用脚本2 - Call multiple scripts through ajax. Script 2 should be called only after Script 1 has finished its execution CSS动画完成后运行JS脚本 - Run js script after css animation is finished JavaScript脚本完成后加载jQuery脚本 - load jQuery script after JavaScript script has finished 网站的javascript完成页面构建后,如何运行Chrome扩展程序内容脚本? - How do I run Chrome extension content script after a site's javascript has finished building page? 在JavaScript中,脚本保证在文档中的前一个脚本运行完毕后运行 - In JavaScript is script guarantied to run after previous scripts in a document finished to run
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM