Answer the question
In order to leave comments, you need to log in
How to properly format an array in Node?
Task: An HTTP request comes to Express. The response should be a formatted array. You need to go to Mongo, extract the documents, and format them into a new array that will be returned. But if you use a for loop, then due to asynchrony it is impossible to know when the entire array is collected, therefore it is also impossible to know when to send a response. Right now I'm using this form:
(function iterateItem(index) {
// Форматирование и вставка элемента массива
iterateItem(index + 1); // Переход ко второму элементу или, если элемент последний, отправка ответа в Express
})(0);
Answer the question
In order to leave comments, you need to log in
After Mongo, you won't have to format anything if you know how to work with it
. In general, your question is not bad.
example
function(req, res)
db.collection().exec((err,result)=>{
let result = result.map(....)
res.send({result})
})
function iterateItem (array, callback){
var result = array.map(el=> return el+1)
callback(result)
}
iterateItem(array, function(result){
res.send(result)
})
Array.prototype.asyncEach = function (each, done) {
var i = -1, a = this
function iter() {
if (++i === a.length) { done && done(); return }
each.call(a, a[i], iter)
}
iter()
}
// Example
;(new Array(10)).asyncEach(function (item, next) {
setTimeout(function () {
console.log("tick")
next()
}, 1000)
}, function () {
console.log("done")
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question