Skip to content

Commit

Permalink
Add timeout option (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiaskern authored and sindresorhus committed May 14, 2017
1 parent eaa8259 commit 744ae79
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
6 changes: 6 additions & 0 deletions index.js
@@ -1,4 +1,6 @@
'use strict';
const pTimeout = require('p-timeout');

module.exports = (emitter, event, opts) => {
let cancel;

Expand Down Expand Up @@ -55,5 +57,9 @@ module.exports = (emitter, event, opts) => {

ret.cancel = cancel;

if (typeof opts.timeout === 'number') {
return pTimeout(ret, opts.timeout);
}

return ret;
};
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -41,6 +41,9 @@
"promises",
"bluebird"
],
"dependencies": {
"p-timeout": "^1.1.1"
},
"devDependencies": {
"ava": "*",
"delay": "^1.3.1",
Expand Down
7 changes: 7 additions & 0 deletions readme.md
Expand Up @@ -93,6 +93,13 @@ pEvent(emitter, 'finish', {multiArgs: true}).then(result => {
});
```

##### timeout

Type: `Number`<br>
Default: `Infinity`

Time in milliseconds before timing out.


## Before and after

Expand Down
25 changes: 25 additions & 0 deletions test.js
Expand Up @@ -95,3 +95,28 @@ test('event to promise - error', async t => {

t.deepEqual(await m(emitter, 'error'), new Error('💩'));
});

test('`timeout` option rejects when short enough', async t => {
const emitter = new EventEmitter();
const timeout = 50;

delay(200).then(() => {
emitter.emit('🦄', '🌈');
});

await t.throws(m(emitter, '🦄', {
timeout
}), `Promise timed out after ${timeout} milliseconds`);
});

test('`timeout` option resolves when long enough', async t => {
const emitter = new EventEmitter();

delay(200).then(() => {
emitter.emit('🦄', '🌈');
});

t.is(await m(emitter, '🦄', {
timeout: 250
}), '🌈');
});

0 comments on commit 744ae79

Please sign in to comment.