diff --git a/src/__tests__/LDClient-test.js b/src/__tests__/LDClient-test.js index 00cefe7a..260010fe 100644 --- a/src/__tests__/LDClient-test.js +++ b/src/__tests__/LDClient-test.js @@ -71,6 +71,28 @@ describe('LDClient', function() { }); }); + it('should resolve waitUntilReady promise after ready event was already emitted', function(done) { + var user = { key: 'user' }; + var handleInitialReady = sinon.spy(); + var handleReady = sinon.spy(); + var client = LDClient.initialize('UNKNOWN_ENVIRONMENT_ID', user, { + bootstrap: {} + }); + + client.on('ready', handleInitialReady); + + setTimeout(function () { + client.waitUntilReady().then(handleReady); + + setTimeout(function () { + expect(handleInitialReady.called).to.be.true; + expect(handleReady.called).to.be.true; + done(); + }, 0); + }, 1000); + }); + + it('should log an error when initialize is called without an environment key', function(done) { var user = {key: 'user'}; var errorSpy = sinon.spy(console, 'error'); diff --git a/src/index.js b/src/index.js index 937f12b5..a336da3f 100644 --- a/src/index.js +++ b/src/index.js @@ -34,6 +34,8 @@ var flushInterval = 2000; var seenRequests = {}; +var ldPromise = Promise.reject(messages.clientNotReady()); + function sendIdentifyEvent(user) { enqueueEvent({ kind: 'identify', @@ -82,9 +84,7 @@ function sendGoalEvent(kind, goal) { } function waitUntilReady() { - return new Promise(function(resolve) { - client.on('ready', resolve); - }); + return ldPromise; } function identify(user, hash, onDone) { @@ -388,6 +388,11 @@ function initialize(env, user, options) { window.addEventListener('message', handleMessage); + var onReady = client.on('ready', function () { + ldPromise = Promise.resolve(client); + client.off(onReady); + }); + return client; } diff --git a/src/messages.js b/src/messages.js index 86086f8f..f68eba3c 100644 --- a/src/messages.js +++ b/src/messages.js @@ -1,4 +1,7 @@ module.exports ={ + clientNotReady: function() { + return 'LaunchDarkly client is not ready'; + }, invalidKey: function() { return 'Event key must be a string'; },