H
H
Hellas2016-09-27 15:07:21
JavaScript
Hellas, 2016-09-27 15:07:21

How to get values ​​for each element in an array?

You need to get all the tags and their data:

tagsController.get = function(req, res, next) {
  tags.getTags(0, -1, function(err, tags) {
    if (err) {
      return next(err);
    }

    var data = {
      tags: tags,
      title: '#'
    };
    res.render('tags', data);
  });
};

We turn to the function getTagsand get the tags, as well as the values ​​for each of them:
Tags.getTags = function(start, stop, callback) {
    db.getSetMembers('tags:id', function(err, tags) {
      if (err) {
        return callback(err);
      }

      // console.log(tags) = [ '1', '2', '3' ]
      
      tags.forEach(function(tag) {
        async.parallel({
          id: function(next) {
            db.getObjectField('tag:' + tag, 'id', next);
          },
          tagname: function(next) {
            db.getObjectField('tag:' + tag, 'tagname', next);
          },
          tagslug: function(next) {
            db.getObjectField('tag:' + tag, 'tagslug', next);
          }
        }, function (err, results) {
          if (err) {
            return callback(err);
          }

          callback(null, results);
        });
      });

    });
  };

In the end, it should look something like this:
"data.tags":[{"id":1,"tagname":"","tagslug":""},{"id":2,"tagname":"","tagslug":""},{"id":3,"tagname":"","tagslug":""}]

But it gives an error Can't set headers after they are sent.
How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2016-09-27
@LiguidCool

In my opinion, you screwed up with async. Doesn't the callback fire before the foreach completes?
In addition, they also write to you that you can’t send headers if something has already gone.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question