NodeJS 7:EventEmitter + await / async [英] NodeJS 7: EventEmitter + await/async

查看:234
本文介绍了NodeJS 7:EventEmitter + await / async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从传递给事件发射器的回调中结束 async 函数而不会使事件发射器

How we can end an async function from a callback passed to an event emitter without promisifing the event emitter?

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

Also without using external modules, just plain NodeJS 7.x/8.x (Which supports Es6 syntax and async/await.

我们基本上想要混合异步函数.. 。带有事件发射器,以便在事件发射器信号结束时解析。

We want basically to mix an async function ... with an event emitter, so that it resolves when the event emitter signals end.

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

Also bear in mind that we won't start with the event emitter until done with some other async functions, using await.

如果我们有一个新的承诺(...),我们会调用resolve();头痛就会结束,但在'异步'中没有'解决',加上我们不能使用'return'因为我们在回调中。

If we had a "new Promise(...)" we would call resolve(); and the headache would be over, but in 'async' there's no 'resolve', plus we cannot use 'return' because we're inside a callback.

/*
 * 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; ?
  });
}



免责声明



如果这个问题已在某个地方完成,我想道歉。完成的研究显示了与同步逻辑混合异步相关的问题,但我没有发现这一点。

Disclaimer

I want to apologize if this question is already done somewhere. The research done shows questions related to mix async with sync logic, but I've found nothing about this.

标题中的类似问题是这个'使用EventEmitter写'异步函数'但它与此问题无关。

A similar question in title is this 'write async function with EventEmitter' but it has nothing to do with this question.

推荐答案


我们可以从传递给事件发射器的回调中结束异步函数而不会使事件发射器失效吗?

Can we end an async function from a callback passed to an event emitter without promisifing the event emitter?

async / await 语法只是然后调用的糖依赖承诺。

No. async/await syntax is just sugar for then calls and relies on promises.

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

  // Here we create an 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 >:)');
}

这篇关于NodeJS 7:EventEmitter + await / async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆