Поскольку мы говорим о нескольких файлах, могу я предложить создать функцию readAsync
и передать ей некоторые параметры ('utf8'
здесь) и callback
?
function readAsync(file, callback) {
fs.readFile(file, 'utf8', callback);
}
После этогомы могли бы map
закончить асинхронно и попытаться прочитать содержимое, например так:
// we're passing our files, newly created function, and a callback
async.map(files, readAsync, (err, res) => {
// res = ['file 1 content', 'file 2 content', ...]
});
Я полагаю, что вы можете сократить весь процесс до этого:
// Let's put everything inside of one function:
function testAsync() {
const files = ['file1.json', 'file2.json', 'file3.json'];
async.map(files, fs.readFile, function (err, data) {
for(let file of files) {
console.log( file.toString() );
}
});
}
Вот пример кода с использованием обещаний:
function readFromFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
console.log(err);
reject(err);
}
else {
resolve(JSON.parse(data));
}
});
});
}
// First, an array of promises are built.
// Each Promise reads the file, then calls resolve with the result.
// This array is passed to Promise.all(), which then calls the callback,
// passing the array of results in the same order.
const promises = [
readFromFile('result1.json'),
readFromFile('result2.json')
// ETC ...
];
Promise.all(promises)
.then(result => {
baseList = result[0];
currentList = result[1];
// do more stuff
});