U
U
Urukhayy2017-07-02 09:13:08
JavaScript
Urukhayy, 2017-07-02 09:13:08

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

What do you advise?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
emp1re, 2017-07-02
@Urukhayy

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

if about the request to express, there are a lot of options, well, I like to use async, but you can also use promisse or even a regular constructor, but what’s here and a regular callback will do
function iterateItem (array, callback){
  var result = array.map(el=> return el+1)
  callback(result)
}
iterateItem(array, function(result){
  res.send(result)
})

L
Leo Developer, 2017-07-02
@crazy_leo

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 question

Ask a Question

731 491 924 answers to any question