节点异步库filterLimit始终返回未定义

时间:2019-07-17 23:50:03

标签: javascript node.js async-await node-async

我正在尝试异步过滤文件路径列表,以仅返回现有文件。我正在将async库的filterLimitfs-extra一起使用。功能如下:

const asyncFilter = require('async').filterLimit;
const fsExtra = require('fs-extra');

async function filterFiles(fileList){
  const existing = await asyncFilter(fileList, 5, (file, callback) => {
    console.log(file); // looks good

    fsExtra.pathExists(file, (err, exists) => {
       const result = err ? false : exists;
       console.log(result); // looks good (boolean)

       callback(null, result);
    });
  });

  console.log(existing); // always undefined...
}

1 个答案:

答案 0 :(得分:1)

编辑2:以下两个建议均无效...这是一个有效版本,其中已弃用的fs.exists()被替换为fs.access()

const async = require('async');
const fs = require('fs');

async function filterFiles(fileList) {
    try {

        const result = await async.filterLimit(fileList, 5, function(filePath, callback) {
            fs.access(filePath, function(err) {
                callback(null, !err)
            });
        });

        console.log(result);
    } catch(err) {
        console.log(err);
    }
};

您不能简单地这样做:

不工作

    const asyncFilter = require('async').filterLimit;
    const fs = require('fs');

    async function filterFiles(fileList) {
        let result = [];
        await asyncFilter(fileList, 5, fs.exists, function(existing) {
            // array of existing files
            console.log(existing);
            // now assign the existing files to result array
            result = existing;
        });
        // should be the same as existing in callback function
        console.log(result);
    };

不需要fs-extra。我认为您的问题是async.filterLimit()不会返回任何内容,而是执行一个回调函数,因此,仅将async.filterLimit()分配给变量并不意味着您会在其中获得结果,{{1 }},因为该函数不返回任何内容!

编辑:基于@Jaromanda X的评论,从上面改编了摘录:

undefined