【发布时间】:2020-08-16 10:18:30
【问题描述】:
假设这是我的代码(只是我写的一个示例来展示这个想法)
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");
});
}
编辑:我不想简单地将下一个脚本添加到前一个脚本的末尾并放弃主文件,因为我不知道它将持续多长时间并且它应该被设计为能够占用在我们的开发阶段之后的其他脚本。我不能只使用现有的包,因为公司的审批时间最多需要两周,我更需要这个
双重编辑:这是我所有的代码,每个脚本和函数都是我编写的,所以我可以让被调用的脚本做需要的事情
【问题讨论】:
-
extract.Start()是否返回承诺? -
我将如何做到这一点?我写了它们,所以无论我想要它返回什么,我只是不确定在哪里或如何
-
您必须为
extract.Start()和rescore.Start();发布一个简单的最小完整可验证代码示例 -
添加到帖子中,它显示了第一个和最后一个脚本,两者功能相同(以读取流开始,以写入流结束)
标签: javascript node.js asynchronous promise callback