首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >await findOneAndUpdate没有等待

await findOneAndUpdate没有等待
EN

Stack Overflow用户
提问于 2019-12-04 13:27:40
回答 1查看 626关注 0票数 0

我有一个函数,我需要带一些ids来使用acyn和await填充findOneAndUpdate im上的更新,但是findoneandupdate运行在其他的之前……不知道为什么

代码语言:javascript
复制
async function update(req, res) {
    const update = req.body;

    await Something1.findOne({
        'id_Something1': update.something1_id
    }).exec((err, something) => {
        if (err || !something) {
            return res.status(500).send({
                message: 'Error'
            })
        }
        update.something1= something._id;
    });


    await Collection.findOneAndUpdate({
        'id_something1': update.custom_id
    }, update, (err, Updated) => {
        console.log('this should show after the first find but it doesnt');
        if (err) {
            return res.status(500).send({
                error: err.errmsg
            });
        } else if (!sociosUpdated) {
            return res.status(500).send({
                message: 'Error'
            });
        }
        res.status(200).send({
            data_updated: Updated
        });
    });
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-04 13:59:54

问题是你在使用async/await的同时也在使用asynchronous。您可以尝试以下代码:

代码语言:javascript
复制
async function update(req, res) {
   const update = req.body;

   try {
      const something =  await Something1.findOne({
          'id_Something1': update.something1_id
        }).exec();

      update.something1 = something && something._id;

      const Updated = await Collection.findOneAndUpdate({
        'id_something1': update.custom_id
      }).exec();

      return res.status(200).send({
        data_updated: Updated
      });
   }
   catch(err) {
       return res.status(400).send(err);
   } 
 });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59169457

复制
相关文章

相似问题

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