Answer the question
In order to leave comments, you need to log in
Loop with NodeJS async, how to do it right?
For example, there is a loop that goes through an array of data, and searches for this data in the database using mongoose.
Code example :
// Модель mongoose
var Data = mongoose.model('data', DataSchema);
// Каой-то массив с данными которые нужно выбрать из БД
var searchData = [...];
// Цикл
searchData.forEach( el => {
// Выборка данных
Data.findOne({'el' : el})
.then(function(result) {
// Получив результат допустим пушим в другой массив для дальнейшего использования
dataResultArray.push(result)
})
})
Answer the question
In order to leave comments, you need to log in
Yes, you can via async/await.
First, wrap all your code in an async function.
(async () => {
// some code...
let dataResultArray = [];
for(let el of searchData) {
const result = await Data.findOne({'el' : el});
dataResultArray.push(result);
}
console.log(dataResultArray);
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question