await-first

2018-11-10 admin

await-first是什么

什么是await-first,Wait the first event in a set of event emitters and event pairs, then clean up after itself.

await-first使用教程帮助文档

await-first

Wait the first event in a set of event pairs, then clean up after itself.

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Install

$ npm install await-first --save

Example

  • awaitFirst(ee, events)
const EventEmitter = require('events');
const awaitFirst = require('await-first');

async function waitMessageOrClose(ee) {
  const o = await awaitFirst(ee, [ 'message', 'close' ]);

  switch (o.event) {
    case 'message':
      const msg = o.args[0]; // [ 'hello world' ]
      console.log('new message =>', msg);
      break;
    case 'close':
      console.log('closed');
      break;
  }
}

const ee = new EventEmitter();
waitMessageOrClose(ee);

setTimeout(() => {
  ee.emit('message', 'hello world');
}, 1000);
  • obj.awaitFirst(events)
const net = require('net');
const awaitFirst = require('await-first');

async function connect() {
  const socket = net.connect(8080, '127.0.0.1');
  socket.awaitFirst = awaitFirst;

  try {
    // wait `connect` or `error` event
    await socket.awaitFirst([ 'connect', 'error' ]);
  } catch (err) {
    console.log(err);
  }
  // ...
}

connect();

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-45032.html

文章标题:await-first

回到顶部