Reputation: 1918
Currently I am trying to have an async function which has another function inside like this:
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;
}
});
}
Then I have a route, which calls this function, like this:
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();
The return results.join("\r\n");
isn't 'returning' the processFile.
How can I achieve this?
Upvotes: 0
Views: 76
Reputation: 8617
My suggestion is to split up your conversion of line reader from cb to a promise doing something like this:
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
});
Then handling your transform back in your async/await world like this:
let data;
let lines = await tokenizer.processFile(req, 'tokenize');
let results = await Promise.map(lines, async (line) => {
return await Transform(line);
}, { concurrency: 80 });
Upvotes: 1