【问题标题】:NodeJS 7: EventEmitter + await/asyncNodeJS 7:EventEmitter + 等待/异步
【发布时间】:2018-02-08 13:23:25
【问题描述】:

我们如何从传递给事件发射器的回调中结束 async 函数而不承诺事件发射器

同样不使用外部模块,只需简单的NodeJS 7.x/8.x(支持Es6语法和async/await

我们希望基本上将async function ... 与事件发射器混合,以便在事件发射器发出end 信号时解决。

另外请记住,在使用 await 完成其他一些异步函数之前,我们不会从事件发射器开始。

如果我们有一个“新的 Promise(...)”,我们会调用 resolve();并且头痛会结束,但是在“异步”中没有“解决”,而且我们不能使用“返回”,因为我们在回调中。

/*
 * Example of mixing Events + async/await.
 */

// Supose a random pomise'd function like:
function canIHazACheezBurger () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(Math.random() > 0.5);
    }, 500 + Math.random() * 500)
  });
}

/**
 * Then, we want to mix an event emitter with this logic,
 * what we want is that this function resolves the promise
 * when the event emitter signals 'end' (for example).
 * Also bear in mind that we won't start with the event emitter
 * until done with the above function.
 * If I had a "new Promise(...)" I would call resolve(); and the
 * headache would be over, but in 'async' there's no 'resolve',
 * plus I cannot use 'return' because I'm inside a callback.
 */
async function bakeMeSomeBurgers () {
  let canIHave = await canIHazACheezBurger();
  // Do something with the result, as an example.
  if (canIHave) {
    console.log('Hehe, you can have...');
  } else {
    console.log('NOPE');
  }
  // Here invoke our event emitter:
  let cook = new BurgerCooking('cheez');
  // Assume that is a normal event emitter, like for handling a download.
  cook.on('update', (percent) => {
    console.log(`The burger is ${percent}% done`);
  });
  // Here lies the problem:
  cook.on('end', () => {
    console.log('I\'ve finished the burger!');
    if (canIHave) {
      console.log('Here, take it :)');
    } else {
      console.log('Too bad you can\'t have it >:)');
    }
    // So, now... What?
    // resolve(); ? nope
    // return; ?
  });
}

免责声明

如果这个问题已经在某个地方完成,我想道歉。所做的研究显示了与混合异步与同步逻辑相关的问题,但我对此一无所知。

标题中类似的问题是this 'write async function with EventEmitter',但与本问题无关。

【问题讨论】:

  • 不,使用async/await 是不可能的,而不承诺你正在等待的东西。
  • 太糟糕了,谢谢!这就是我想知道的。所以我想我将开始编写一个特定于域的承诺者 o 从事件发射器返回承诺......

标签: javascript node.js asynchronous


【解决方案1】:

我们能否在不承诺事件发射器的情况下从传递给事件发射器的回调中结束异步函数?

async/await 语法只是 then 调用的糖并依赖于承诺。

async function bakeMeSomeBurgers () {
  let canIHave = await canIHazACheezBurger();
  if (canIHave)
    console.log('Hehe, you can have...');
  else
    console.log('NOPE');

  // Here we create and await our promise:
  await new Promise((resolve, reject) => {
    // Here invoke our event emitter:
    let cook = new BurgerCooking('cheez');
    // a normal event callback:
    cook.on('update', percent => {
      console.log(`The burger is ${percent}% done`);
    });
    cook.on('end', resolve); // call resolve when its done
    cook.on('error', reject); // don't forget this
  });

  console.log('I\'ve finished the burger!');
  if (canIHave)
    console.log('Here, take it :)');
  else
    console.log('Too bad, you can\'t have it >:)');
}

【讨论】:

  • 包装事件发射器的 end 方法是我没有想到的,太好了!
  • @SigmaSoldier 嗯,这正是我所理解的“承诺事件发射器”:-)
  • 我想到了像util.promisify这样的方法,但是在Node 7.x中不可用(所以我现在不能在Electron中使用它),但我没想到这么简单优雅的方式^^
猜你喜欢
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 2019-07-20
  • 2020-03-31
  • 2019-06-30
  • 2019-08-08
  • 1970-01-01
  • 2021-05-25
相关资源
最近更新 更多