Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.