【问题标题】:Mongoose doesn't yield findeOne results in coMongoose 不会在 co 中产生 findeOne 结果
【发布时间】:2016-10-15 18:30:00
【问题描述】:

我正在使用 co 和 mongoose,我希望我的异步代码看起来更“同步”,并且 - 据我所知 - co 库允许我在另一个中使用来自一个产生的承诺的数据,以避免回调地狱。它似乎适用于猫鼬保存(即使我进行了多次保存),但它对从 find() 或 findOne() 等查询返回的承诺没有任何作用。这是为什么?我能做些什么来解决它?

这是我的一段代码:

co(function *() {
    let unhashedPassword = Math.random().toString(36);
    let passed = {
        username: 'T1',
        password: bcrypt.hashSync(unhashedPassword)
    };
    let saved = yield new test_model(passed).save();
    console.log("saved: " + saved);
    let found = yield test_model.findOne({username: saved.username}).exec();
    console.log("found" + found);
});

还有输出:

saved: { _id: 57606dcf0f2378d41c355acd,
  password: '...',
  username: 'T1',
  __v: 0 }
Process finished with exit code 0

【问题讨论】:

  • 如果你只输入console.log("found"); 会怎样?它达到那个地步了吗?看起来很奇怪,你甚至都看不到 console.log 的输出
  • 尝试捕捉错误like here。我很确定你有一个例外。
  • @WillemD'Haeseleer,我是在提交 test_model.findOne() 之后完成的,但它没有被打印出来——它没有达到那个程度。
  • @Bergi - 在 co 之后添加了 catch,甚至通过 try/catch 包围了 findOne,但仍然没有...

标签: node.js mongoose promise ecmascript-6 co


【解决方案1】:

当你尝试这个时你会看到什么?

co(function *() {
    let unhashedPassword = Math.random().toString(36);
    let passed = {
        username: 'T1',
        password: bcrypt.hashSync(unhashedPassword)
    };
    let saved = yield new test_model(passed).save();
    console.log('saved: ', saved);
    let foundPromise = test_model.findOne({username: saved.username}).exec()
    .then(function(value){
        console.log('fulfilled', value);
    }, function(error){
        console.log('error', error);
    });
    console.log('foundPromise', foundPromise);
    let found = yield foundPromise;
    console.log('found', found);
}).catch(function(error){
    console.log('catch', error);
});

【讨论】:

  • 我删除了最后一个收益(let found = yield foundPromise yield):已保存:{_id:57607fcf7cfca7980d37bc12,密码:'$2a$10$Ebk6vFc5iai7yt7wTnT16e.0fOxEyvUE0jUqemYho44MfLUiACI0u','0',用户名:'T } foundPromise Promise {emitter: EventEmitter { domain: null, _events: { reject: [Function] }, _eventsCount: 1, _maxListeners: undefined }, emit: {}, end: true } 进程以退出代码 0 结束
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多