0

So I am trying to use co to wrap around MongoDB methods that return promises eg http://mongodb.github.io/node-mongodb-native/2.0/reference/ecmascript6/crud/

I see co being used like:

co(function*() {

which seems like an anonymous function. Fine in the main body of your code, but is there a way to get at the values yielded inside? eg to basically get at the results of the co routine:

If I could do:

let wrap = co(function* (collName) {
  let res = yield collection.findOne({});
  yield res;
});

and then elsewhere

let res = wrap("Topics");

but I get

TypeError: wrap is not a function

Tried also:

co(function* wrap(collName) {

...

co.call(this, wrap("Topics"));
let wrap = co.wrap(function* (collName) { ...

but still no luck.

dcsan
  • 7,487
  • 10
  • 50
  • 80
  • What exactly do you mean by "*a way to get at the values yielded inside*"? No, the values inside the generator are asynchronously produced, you cannot access them from the outside synchronously. The result is always a promise. – Bergi Mar 03 '16 at 09:07
  • does typescript async / await enable this then? – dcsan Mar 03 '16 at 17:59
  • No, there is absolutely no way to make asynchronous things synchronous. Even ES8 `async` functions will only return promises, and the plain `await`ed values are only available on the inside. – Bergi Mar 03 '16 at 19:06

1 Answers1

1

I think what you're looking for is the co.wrap function.

let wrap = co.wrap(function* (collName) {
  let res = yield collection.findOne({});
  yield res;
});

Then you can use it in the way you want

let res = wrap("Topics");
Cameron Martin
  • 5,764
  • 1
  • 35
  • 52
  • that returns a promise, when i'm actually looking for the result of the `findOne` ... – dcsan Mar 03 '16 at 17:57
  • As other people have said, you cannot do that. When the promise-returning function returns, the value inside the promise won't even be there yet. – Cameron Martin Mar 03 '16 at 19:18