1

I have a function that does something asynchronously, e.g.,

const doSomething = () => {
  request(url)
  .pipe(hasher)
  .on('finish', () => {
    // "return" only here
    return hasher.read();
  });
});

I would now like to "wait" in the function until hasher.read() can be returned instead of returning early with undefined (which is what the above variant does).

Ideally, I'd use doSomething as

const out = yield doSomething();

Any hints?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • Are you familiar with [How do I return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/710446) – apsillers Dec 11 '15 at 20:40

1 Answers1

0

What about using deferred:

const q = require('q');

const doSomething = () => {
  const d = q.defer();

  request(url)
  .pipe(hasher)
  .on('finish', () => {
    // "return" only here
    d.resolve(hasher.read());
  });

  return d.promise;
});

Then you can handle it as a promise and use yield.

dsdenes
  • 1,025
  • 6
  • 15