【问题标题】:Then executes before the query is done然后在查询完成之前执行
【发布时间】:2018-06-01 06:32:09
【问题描述】:

我昨天遇到了这个问题,但为了问这个问题,我要求解决方案,所以我什么都没学到。我的代码如下所示:

User.findOne({'user.id': author.id}, 'id', function (err, userid) {

  console.log(userid); //(1) executes after (2)
  newCharacter.character.author = userid;

}).then(() => {

  console.log('does it work? '+newCharacter.character.author); //(2) executes before (1): undefined

  newCharacter.save(function(err, character) {
    console.log('Success! ' +character.id);
  });
});

当我将userid 登录到then 时,由于某种原因它仍然未定义。为什么会这样?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您正在混合回调和承诺。我认为不能保证附加到findOne 的回调将在then 开始执行之前完成。

    您可能想要做的是将用户 ID 传递给 then

    User.findOne({'user.id': author.id}, 'id'})
      .then(userid => {
        newCharacter.character.author = userid;
        console.log('does it work? '+newCharacter.character.author);
        newCharacter.save(function(err, character) {
          console.log('Success! ' +character.id);
        });
      });
    

    我发现此资源对理解 Promise 非常有帮助:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2019-11-26
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      相关资源
      最近更新 更多