P
P
Pavel Tkachenko2018-05-18 15:22:35
Node.js
Pavel Tkachenko, 2018-05-18 15:22:35

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)
        })
})

MB via asycn but has not yet figured out how to implement it correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zlatoslav Desyatnikov, 2018-05-18
@Pavel_Tkachenko

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 question

Ask a Question

731 491 924 answers to any question