Skip to content

Commit

Permalink
feat: impl willReady
Browse files Browse the repository at this point in the history
  • Loading branch information
killagu committed Jun 26, 2018
1 parent ac54afa commit 901b694
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ install:
test_script:
- node --version
- npm --version
- npm run ci
- npm run test

build: off
17 changes: 15 additions & 2 deletions lib/ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const once = require('once');
const ready = require('get-ready');
const uuid = require('uuid');
const debug = require('debug')('ready-callback');
const WILL_READY_CALLBACKS = Symbol('willReadyCallbacks');
const TRIGGER_WILL_READY = Symbol('triggerWillReady');

const defaults = {
timeout: 10000,
Expand All @@ -29,12 +31,13 @@ class Ready extends EventEmitter {
this.opt = opt || {};
this.isError = false;
this.cache = new Map();
this[WILL_READY_CALLBACKS] = [];

setImmediate(() => {
// fire callback directly when no registered ready callback
if (this.cache.size === 0) {
debug('Fire callback directly');
this.ready(true);
this[TRIGGER_WILL_READY]();
}
});
}
Expand All @@ -52,6 +55,7 @@ class Ready extends EventEmitter {
// delegate API to object
obj.ready = this.ready.bind(this);
obj.readyCallback = this.readyCallback.bind(this);
obj.willReady = this.willReady.bind(this);

// only ready once with error
this.once('error', err => obj.ready(err));
Expand Down Expand Up @@ -121,11 +125,20 @@ class Ready extends EventEmitter {

if (this.cache.size === 0) {
debug('[%s] Fire callback async', id);
this.ready(true);
this[TRIGGER_WILL_READY]();
}
return this;
}

willReady(fn) {
this[WILL_READY_CALLBACKS].push(fn);
}

[TRIGGER_WILL_READY]() {
return Promise.all(this[WILL_READY_CALLBACKS].map(fn => fn()))
.then(() => this.ready(true))
.catch(e => this.ready(e));
}
}

// Use ready-callback with options
Expand Down
15 changes: 15 additions & 0 deletions test/ready.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -462,4 +462,19 @@ describe('Ready', function() {
assert(ready.obj === obj1);
assert(ready.obj !== obj2);
});

describe('willReady', function() {
it('should fire willRead callbacks before ready', function() {
const obj = new EventEmitter();
const ready = new Ready();
ready.mixin(obj);
const endA = obj.readyCallback('a');
const spyWillReady = spy();
obj.willReady(spyWillReady);
setTimeout(endA, 1);
setTimeout(function() {
assert.strictEqual(spyWillReady.callCount, 1);
}, 10);
});
});
});

0 comments on commit 901b694

Please sign in to comment.