首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查询未正常工作时在forEach内推送

查询未正常工作时在forEach内推送
EN

Stack Overflow用户
提问于 2020-06-23 05:43:39
回答 1查看 217关注 0票数 0

我正在使用mongodb缝合/领域,并尝试使用foreach修改数组中的对象,并将ids推送到新的数组中。

对于我正在修改的每个对象,我也首先执行一个查询,在找到文档后,我开始修改对象,然后将id推入另一个数组中,以便以后可以同时使用这两个数组。

代码如下所示:

代码语言:javascript
复制
exports = function(orgLoc_id, data){
    var HttpStatus = require('http-status-codes');  
    // Access DB
    const db_name = context.values.get("database").name;
    const db = context.services.get("mongodb-atlas").db(db_name);
    const orgLocPickupPointCollection = db.collection("organizations.pickup_points");
    const orgLocStreamsCollection = db.collection("organizations.streams");
    const streamsCollection = db.collection("streams");
      
    let stream_ids = [];    
  
    data.forEach(function(stream) {
  
      return streamsCollection.findOne({_id: stream.stream_id}, {type: 1, sizes: 1}).then(res => { //if I comment this query it will push without any problem
        if(res) {
          let newId = new BSON.ObjectId();
          stream._id = newId;
          stream.location_id = orgLoc_id;
          stream.stream_type = res.type;
          stream.unit_price = res.sizes[0].unit_price_dropoff;
          stream._created = new Date();
          stream._modified = new Date();
          stream._active = true; 
    
          stream_ids.push(newId);
                              
        }
      })
    })    
    console.log('stream ids: ' + stream_ids);

    //TODO

  };

但是,当我尝试登录'stream_ids‘时,它是空的,并且什么也没有显示。未分配属性stream_type和unit_price。

我试过许诺,但没有成功

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-23 06:00:51

这是一个异步问题。在回调中填充数组的值。但由于事件循环的性质,在执行console.log时不可能调用任何回调函数。

你提到了一个涉及承诺的解决方案,这可能是正确的策略。例如,如下所示:

代码语言:javascript
复制
exports = function(orgLoc_id, data) {
  // ...
  let stream_ids = [];
  const promises = data.map(function(stream) {
    return streamsCollection.findOne({ _id: stream.stream_id }, { type: 1, sizes: 1 })
      .then(res => { //if I comment this query it will push without any problem
        if (res) {
          let newId = new BSON.ObjectId();
          // ...
          stream_ids.push(newId);
        }
      })
  })

  Promise.all(promises).then(function() {
    console.log('stream ids: ' + stream_ids);

    //TODO
    // any code that needs access to stream_ids should be in here...
  });
};

请注意将forEach更改为map...that的方式,您将获得一个包含所有promise的数组(我假设您的findOne由于.then而返回promise)。

然后使用Promise.all等待解析所有承诺,然后就应该拥有数组了。

附注:一种更优雅的解决方案是在.then中返回newId。在这种情况下,Promise.all实际上将解析所有promises的结果数组,这将是newId的值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62523967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档