NodeGuy / server-date

Make the server's clock available in the browser.
http://www.nodeguy.com/serverdate/
Mozilla Public License 2.0
193 stars 53 forks source link

Synchronize api method #28

Closed azaslavsky closed 8 years ago

azaslavsky commented 8 years ago

This PR does two things: first, it allows API consumers to manually fire the synchronization routine. This method accepts an optional completion callback, which returns with three parameters: a boolean indicating whether or not the sync was successful, the new target value, and the old target value. An example:

ServerDate.sync(function(success, newTarget, oldTarget) {
  if (success) {
    console.log('Yay, the synchronization was successful!');
  } else {
    console.log('Boo, the synchronization failed!');
  }
});

The second addition is to allow binding/unbinding of listeners that fire whenever a synchronization finishes/times out. An example:

var mySyncCallback = function(success, newTarget, oldTarget) {
  console.log('Sync completed');
});

ServerDate.on(mySyncCallback);
ServerDate.sync(); // -> Sync completed
ServerDate.off(mySyncCallback); // ServerDate.off() is also acceptable to remove all listeners
ServerDate.sync(); // There will be no console logging at the end of this sync, since all listeners have been removed
NodeGuy commented 8 years ago

Interesting, thank you for your contribution. How about we have sync return a promise instead of taking a callback and use the promise semantics for indicating success or failure rather than a boolean?

For listeners I'd like the API to be consistent with Node's Events.

azaslavsky commented 8 years ago

Wouldn't we need an external dependency to support promises? Or are you proposing to use the ES6 implementation? Either way, I'll be honest and say that my knowledge of promises is not as robust as it should be. Are you suggesting returning the promise object itself instead of the boolean from the callback?

NodeGuy commented 8 years ago

We don't need an external dependency to support promises (although I wouldn't be against that). All we need to do is to return an object which is conformant with the Promise specification, i.e., an object with a then method.

I'm suggesting that there is no callback.

Promises already have a standard convention for indicating success or failure (fulfilment or rejection) so I like that better than inventing a new one with a boolean.