gpt4 book ai didi

javascript - 带有嵌套函数的 Node 异步函数

转载 作者:行者123 更新时间:2023-12-03 01:41:54 25 4
gpt4 key购买 nike

目前我正在尝试创建一个异步函数,其中包含另一个函数,如下所示:

processFile: async function(req, whatTo, callback){

const lines = [];

const lineReader = require('readline').createInterface({
input: require('streamifier').createReadStream(req.file.buffer)
});

let errorPresent = false;

lineReader.on('line', line => {
lines.push(line.replace(/ /g,''));
});

lineReader.on('close', async () => {

try {

const results = await Promise.map(lines, async(line) => {

return await Transform(line);

}, { concurrency: 80 });

return results.join("\r\n");

}catch(err){
throw err;
}

});

}

然后我有一个路由,它调用这个函数,如下所示:

const data = await tokenizer.processFile(req, 'tokenize');

res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', 'attachment; filename=tokenized.txt');
res.write(data, 'binary');
res.end();

return results.join("\r\n"); 并不是“返回”processFile。

我怎样才能实现这个目标?

最佳答案

我的建议是将行读取器从 cb 的转换拆分为执行如下操作的 promise :

processFile: (req, whatTo) => new Promise((res,rej)=>{

const lines = [];

const lineReader = require('readline').createInterface({
input: require('streamifier').createReadStream(req.file.buffer)
});

let errorPresent = false;

lineReader.on('line', line => {
lines.push(line.replace(/ /g,''));
});

lineReader.on('close', function(){
res(lines);
});
// UNCAUGHT ERRORS, USE rej() for others
});

然后在异步/等待世界中处理您的转换,如下所示:

let data;
let lines = await tokenizer.processFile(req, 'tokenize');
let results = await Promise.map(lines, async (line) => {
return await Transform(line);
}, { concurrency: 80 });

关于javascript - 带有嵌套函数的 Node 异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50804683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com