简体   繁体   中英

Promise : execute after loop

I want to create several entries in a loop using waterline ORM. Each created object is pushed in an array. After all objects are created, I need to return the full Array.

Here is my code :

share: function(req, res, next) {
    var params = {},
        id = req.param('id'),
        img = {},
        targets;

    if (!req.param('name')) {
      res.status(400);
      return res.json('Error.No.Name')
    }

    var promiseLoop = function(Tree) {      // Function called after creating or finding Tree to attach to
      var array = [];
      if(!req.param('targets')) return Tree; // No targets provided => exit

      targets = JSON.parse(req.param('targets'));
      _.each(targets, function(target) {
        params = {
          target : target,
          image: Tree.id,
          message : req.param('message')
        };

        Leaf
          .create(params)
          .then(function(Leaf) {
            array.push(Leaf);
          });
      });

      Tree.array = array;
      return Tree;
    }

    if (!id) {
      params.owner = req.session.user ;
      params.name = req.param('name');

      Tree
        .create(params)
        .then(function(Tree) {
          res.status(201);  // Status for image creation
          return Tree;
        })
        .then(promiseLoop)
        .then(function(data) { res.status(201); res.json(data);})
        .catch(function(err) { res.status(400); res.json(err);});
    }
  }

};

I want the Tree return to have a array member equal to an array of created Leaves.

But of course the part

  Tree.array = array;
  return Tree;

is executed befure array is populated. and what I get in response is my Tree object :

{
 ...,
 "array": []
}

What wan I do to be sure to execute this part only after all objects are created ?

Thank you by advance.

Promises know when a previous promise is done through then chaining. You can and should utilize that.

Return a promise from promiseLoop :

  var promiseLoop = function(Tree) { // are you sure about that naming?
  if(!req.param('targets')) return Tree;
  targets = JSON.parse(req.param('targets'));
  var leaves = targets.map(function(target){
    return Leaf.create({ //  map each target to a leaf
        target : target,
        image: Tree.id,
        message : req.param('message')
      }); 
  });

  return Promise.all(leaves).then(function(leaves){
      Tree.array = leaves;  // assign to tree
  }).return(Tree); // finally resolve the promise with it
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM