0

I'm trying to make a synchronous query to mongodb with es6 yield feature and when I'm calling my function on my test this apparently does not work.

my function code is the following:

'use strict';

let Notifications, lodash;

lodash = require('lodash')

Notifications = require('../../api/notifications/notifications.model');

function *syncQuery (email, kind, notificationIds) {
  let ids, query, remains;
  query = {
    userEmail: email,
    'notifications.kind' : kind
  };
  return yield Notifications.findOne(query, {}, {lean: true}, (err, usr) => {
    let toNotify;

    if (err) {
      console.log('Error:', err);
      reject(err);
    }
    toNotify = lodash.difference(notificationIds, usr.notifications.id);
    return toNotify;
  });
}

module.exports = syncQuery;

and my module spec is:

  it('should be synchronous', done => {
    let remains = syncQuery(n.user, 'budget', [9, 71, 24, 90, 5]);
    console.log(remains);
    remains.next();
    console.log('we'r here(?)');
    console.log(remains);
    done();
  })

when I run my test the output is the following:

{}
we'r here(?)
{}

Someone related with JS + ES6 who can help me please. My last approach was return a promise on my function but it does not helped me on my duty, I really need to do this job synchronous

PS: is probably that my syntax wasn't be the best(maybe I'm using not the best practices for ES6) and neither my english level (maybe some typo). so, thank even just for read this

Chelo Tavano
  • 63
  • 1
  • 1
  • 5
  • 2
    [You can't use Mongoose/MongoDB synchronously](http://stackoverflow.com/questions/17181248/making-mongoose-js-queries-run-synchronously). If you're using NodeJS, you're going to need to use Async/Promises at some point. Right now, you're just `yield`ing an unexecuted query. Or perhaps, you're looking for something like the [co library](https://www.npmjs.com/package/co). – CodingIntrigue Jan 26 '16 at 16:37
  • 3
    I don't think you understood what `yield` does. You cannot make anything asynchronous into synchronous (and believe me, you don't even *want* to). Learn about promises and ES7 async/await first. Then you're welcome to use generators. – Bergi Jan 26 '16 at 16:50

0 Answers0