如何在nodejs中等待查询结果以更新另一个查询结果

时间:2018-04-16 20:06:06

标签: javascript node.js mongodb asynchronous geospatial

想要在当前用户数据中添加商品查询数据,以便向用户返回他们创建的商品。作为回应,用户提供的始终为null

获取范围距离内的所有用户:

#build map
world <- map_data("world") # we already did this, but we can do it again
map <- ggplot() + geom_polygon(data = world, aes(x=long, y = lat, group = group))
map <- map + coord_map(ylim = c(23.5, 66.5))
map

获取范围距离内的关联用户的所有优惠:

   // Execute Query and Return the Query Results
   query.exec(function(error, associate_users) {
          var array_users = new Array();

          for (var i = 0; i < associate_users.length; i++) {
                var current_user = formatUser(associate_users[i], true);
                var user_id = current_user['user_id'];

                offers_controller.getUserOffers(user_id, latitude, longitude, distance, function(error, result_offers) {

                      current_user['offers'] = result_offers;
                      console.log(result_offers);
                      console.log(current_user); 
                       //Users logs show offers but in array there is no offers in api
          });
          array_users.push(current_user);
       }

       response.json({

           error: false,
           user: array_users,
            message:message.userListed
       });
 }); 

1 个答案:

答案 0 :(得分:0)

您需要嵌套回调:

query.exec(function(error, associate_users) {
  if (error) {
    return callback(error, null);
  } else {
     //TODO Your users loop code
     query.exec(function(error, result_offers) {
       if (error) {
         return callback(error, null);
       } else {
         //TODO Combine the data however you need
         response.json({
           error: false,
           user: array_users,
           message: message.userListed
       });
    }
  }
});