然后在查询完成之前执行

时间:2018-05-31 22:14:31

标签: node.js mongodb mongoose

昨天我遇到了这个问题,但是问我这个问题,我要求解决方案,所以我没有学到任何东西。我的代码看起来像这样:

_auth.signInWithFacebook(accessToken: null);

当我在const escapeStringRegexp = require('escape-string-regexp') const name = 'foo' db.stuff.find({name: new RegExp('^' + escapeStringRegexp(name) + '$', 'i')}) 中记录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); }); }); 时,由于某种原因,它仍然未定义。为什么会这样?

1 个答案:

答案 0 :(得分: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);
    });
  });

我发现这个资源非常有助于理解承诺:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

相关问题