具有嵌套函数的节点异步函数

时间:2018-06-11 19:21:15

标签: javascript node.js

目前我正在尝试使用async函数,其中包含另一个函数:

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。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

我的建议是将你的读卡器从cb转换为承诺做这样的事情:

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