简体   繁体   English

从事件发射器创建生成器

[英]Create generator from event emitter

I have a function that does something asynchronously, eg, 我有一个异步执行某项功能的函数,例如,

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). 我现在想在函数中“等待”,直到可以返回hasher.read()而不是使用undefined早返回(上述变体就是这样做的)。

Ideally, I'd use doSomething as 理想情况下,我会使用doSomething作为

const out = yield doSomething();

Any hints? 有什么提示吗?

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 . 然后,您可以将其作为承诺并使用yield

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM