gpt4 book ai didi

javascript - 如何使用异步函数作为 Array.filter() 的比较函数?

转载 作者:行者123 更新时间:2023-11-29 21:09:27 31 4
gpt4 key购买 nike

对于我正在编写的 Node JS 模块,我想使用异步函数 Stats.isFile() 作为 Array.filter() 的回调函数功能。下面我有一个我想要实现的工作示例,但是使用同步等效项。我不知道如何包装异步函数,以便我可以在 Array.filter() 函数中使用。

const fs = require('fs')

exports.randomFile = function(dir = '.') {
fs.readdir(dir, (err, fileSet) => {
const files = fileSet.filter(isFile)
const rnd = Math.floor(Math.random() * files.length);
return files[rnd])
})
}

function isFile(item) {
return (fs.statSync(item)).isFile()
}

最佳答案

您不能将异步回调与 .filter() 一起使用。 .filter() 需要同步结果,但无法从异步操作中获得同步结果。因此,如果您要使用异步 fs.stat(),则必须将整个操作设为异步。

这是一种方法。请注意,即使 randomFile() 也需要异步返回它的结果。在这里,我们为此使用回调。

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

exports.randomFile = function(dir, callback) {
fs.readdir(dir, (err, files) => {
if (err) return callback(err);

function checkRandom() {
if (!files.length) {
// callback with an empty string to indicate there are no files
return callback(null, "");
}
const randomIndex = Math.floor(Math.random() * files.length);
const file = files[randomIndex];
fs.stat(path.join(dir, file), (err, stats) => {
if (err) return callback(err);
if (stats.isFile()) {
return callback(null, file);
}
// remove this file from the array
files.splice(randomIndex, 1);
// try another random one
checkRandom();
});
}

checkRandom();
});
}

下面是您将如何使用来自另一个模块的异步接口(interface)。

// usage from another module:
var rf = require('./randomFile');
fs.randomFile('/temp/myapp', function(err, filename) {
if (err) {
console.log(err);
} else if (!filename) {
console.log("no files in /temp/myapp");
} else {
console.log("random filename is " + filename);
}
});

关于javascript - 如何使用异步函数作为 Array.filter() 的比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425887/

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