Skip to content

Instantly share code, notes, and snippets.

@jbardon
Last active March 26, 2018 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbardon/da9faa37cfc8cf31c2726cca1923262c to your computer and use it in GitHub Desktop.
Save jbardon/da9faa37cfc8cf31c2726cca1923262c to your computer and use it in GitHub Desktop.
Deferred object with standard Promise API
var event = new Event('build');
window.addEventListener('build', eventHandler, false);
var defer = null;
function eventHandler() {
console.log('Event received');
defer.resolve('hello');
}
function Deferred () { // Wrapper to get Deferred object and promise
var defer = {};
defer.promise = new Promise (function (resolve, reject) {
defer.resolve = resolve.bind(this);
defer.reject = reject.bind(this);
});
return defer;
}
function click() {
defer = new Deferred(); // Create new promise and get deferred object
return defer.promise; // But returns the promise
}
click().then(data => console.log('Click completed', data));
window.dispatchEvent(event);
var resolvePromise = null;
// Async event the click is waiting for
var event = new Event('build');
window.addEventListener('build', eventHandler, false);
function eventHandler() {
console.log('Event received');
resolvePromise('hello');
}
function click() {
return new Promise (function (resolve, reject) {
// Default API doesn't allow to get a deferred object
// No choice but to export the resolve function
resolvePromise = resolve.bind(this);
});
}
// Complete click once the event is received
click().then(data => console.log('Click completed', data));
// Triggers async event for click to resolve the promise
window.dispatchEvent(event);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment