Async функция в app.get()
Задача: Необходимо возвращать с сервера некоторые данные в ответ на get запрос. Есть функция, которая возвращает массив, с ссылками на картинки. Если вызывать функцию вне app.get() - функция отрабатывает корректно и возвращает необходимый массив, однако массив естественно не обновляется, при очередном обращении к адресу. Соответственно необходимо вызывать функцию внутри app.get(), что бы массив обновлялся. Понимаю, что необходимо использовать промисы/коллбэки, но все никак не получается. Буду благодарен любой помощи.
// function to create an array of links to images
function createImagesUrl() {
const images = []
fs.readdir("./upload", { withFileTypes: true },
(err, files) => {
if (err)
console.log(err)
else {
files.forEach(file => {
if (path.extname(file.name) === ".jpg") {
var imgpath = '/upload/' + file.name
images.push(imgpath)
}
})
}
})
return images
}
const imagesUrl = createImagesUrl()
// get random background images from the server
app.get("/uploads", (req, res) => {
res.send(imagesUrl)
console.log(imagesUrl)
})
Спасибо!
Ответы (1 шт):
Автор решения: Pavel Grishaev
→ Ссылка
// function to create an array of links to images
function getImagesUrls( callback ) {
const arr = [];
fs.readdir("./upload", { withFileTypes: true }, (err, files) => {
if (err){
callback(err);
} else {
files.forEach( file => {
if (path.extname(file.name) === ".jpg") {
var imgpath = '/upload/' + file.name;
arr.push(imgpath);
}
})
callback( null, arr );
}
});
}
// get random background images from the server
app.get("/uploads", (req, res) => {
getImagesUrls(( err, arr )=>{
if( err ){
res.send('error');
} else {
res.send( JSON.stringify(arr) );
}
});
});