Answer the question
In order to leave comments, you need to log in
How to write data from asynchronous function?
For example, there is such a function
function getFiles(directoryPath, arrFiles, callback) {
fs.readdir(directoryPath, (err, files) => {
if (err) console.log(err);
... //здесь добавляю в массив файлы
callback(arrFiles);
});
});
var file;
getFiles("./",[], function(result){
file = result;
return file;
});
Answer the question
In order to leave comments, you need to log in
Since two answers cannot be added, this answer will have two parts.
Most likely you are doing something like this:
var file;
getFiles("./",[], function(result){
file = result;
return file;
});
console.log(file);
getFiles("./",[], function(result){
file = result;
return file;
});
file = result;
return file;
getFiles("./",[], function(result){
var file = result;
// Дальше работаем с file здесь
});
function getFiles(directoryPath) {
return new Promise((resolve, reject) => {
fs.readdir(directoryPath, (err, files) => {
let arrFiles = [];
// ... Добавляете в arrFiles нужную информацию
if (err) {
console.log(err);
reject(err);
}
resolve(arrFiles);
});
})
};
// где-то выше
async function someFunction() { // Функция, где находится var file и остальное
// ...
try {
var file = await getFiles("./"); // Здесь await заставит ваш код "ждать", пока из Promise в getFiles не будет вызван resolve
console.log(file);
} catch (e) {
// Сделать что-то с ошибкой
}
// ...
}
var file;
debugger;
getFiles("./",[], function(result){
file = result;
return file;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question