Node.js添加到循环内的对象

时间:2016-03-22 16:48:26

标签: node.js express bluebird

我似乎无法弄清楚这一点。我正在使用Node,Express和Bluebird来兑现承诺。我要做的是添加循环中的对象。当我控制日志时,我得到一个空对象。

我是否认为这一切都错了?

Promise.props({
    rewards: db.query("SELECT title, created_by FROM rewards WHERE team_id = '" + team_id + "'")
}).then(function(results) {
  
    var rewards = [],
    title = results.rewards[0].title;
    created_by = results.rewards[0].created_by,

    for (var i = 0; i < results.rewards.length; i++) {
       Promise.props({
           user: db.query("SELECT * FROM users WHERE uid = '" + results.rewards[i].created_by + "'")
       }).then(function(result) {
            rewards.push({
	        created_by: created_by,
	        title: title,
	        username: result.user[0].username
            });
        });
    }
    console.log(rewards);
});

1 个答案:

答案 0 :(得分:2)

您正在尝试在工作完成之前控制日志。你需要等待承诺的嵌套循环完成,首先。

为此,将所有承诺收集到一个数组中并使用Promise.all知道它们何时完成


var promiseList = [];

for (var i = 0; i < results.rewards.length; i++) {

  // hold the promise in a variable
  var p = Promise.props({
    user: db.query("SELECT * FROM users WHERE uid = '" + results.rewards[i].created_by + "'")
  }).then(function(result) {
    rewards.push({
    created_by: created_by,
    title: title,
    username: result.user[0].username
  });

  // collect the promise
  promiseList.push(p);
}

// wait for all of them to finish
Promise.all(promiseList).then(function(){
  console.log(rewards);
});