0

I'm using co and mongoose and I'd like to my asynchronous code look little more "synchronously" and - as far as I read - co library allows me use data from one yielded promise in another to avoid callback hell. It seems to work with mongoose save (even if I do multiple saves), but it does nothing with promises returned from queries like find() or findOne(). Why is that? What can I do to fix it?

Here'a a piece of my code:

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);
});

And the output:

saved: { _id: 57606dcf0f2378d41c355acd,
  password: '...',
  username: 'T1',
  __v: 0 }
Process finished with exit code 0
Jarosław Rewers
  • 1,059
  • 3
  • 14
  • 23

1 Answers1

1

What do you see when you try this ?

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);
});
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
  • I removed the last yield (let found = yield foundPromise yield): saved: { _id: 57607fcf7cfca7980d37bc12, password: '$2a$10$Ebk6vFc5iai7yt7wTnT16e.0fOxEyvUE0jUqemYho44MfLUiACI0u', username: 'T1', __v: 0 } foundPromise Promise { emitter: EventEmitter { domain: null, _events: { reject: [Function] }, _eventsCount: 1, _maxListeners: undefined }, emitted: {}, ended: true } Process finished with exit code 0 – Jarosław Rewers Jun 14 '16 at 22:07