How To Resolve A Promise Multiple Times?
Solution 1:
How to resolve a promise multiple times?
You can't. Promises can only be resolved once. Once they have been resolved, they never ever change their state again. They are essentially one-way state machines with three possible states pending, fulfilled and rejected. Once they've gone from pending to fulfilled or from pending to rejected, they cannot be changed.
So, you pretty much cannot and should not be using promises for something that you want to occur multiple times. Event listeners or observers are a much better match than promises for something like that. Your promise will only ever notify you about the first event it receives.
I don't know why you're trying to avoid callbacks in this case. Promises use callbacks too in their .then()
handlers. You will need a callback somewhere to make your solution work. Can you explain why you don't just use window.addEventListener('myEvent', someCallback)
directly since that will do what you want?
You could return a promise-like interface (that does not follow Promise standards) that does call its notification callbacks more than once. To avoid confusion with promises, I would not use .then()
as the method name:
functiongetNotifier() {
const event = newEvent('myEvent');
setTimeout(() => {
window.dispatchEvent(event);
}, 500);
setTimeout(() => {
window.dispatchEvent(event);
}, 700);
let callbackList = [];
const notifier = {
notify: function(fn) {
callbackList.push(fn);
}
};
window.addEventListener('myEvent', (data) => {
// call all registered callbacksfor (let cb of callbackList) {
cb(data);
}
});
return notifier;
};
// Usage:getNotifier().notify(data => {console.log(data.type)})
Solution 2:
I have a solution in Typescript.
exportclassPromiseParty {
privatepromise: Promise<string>;
privateresolver: (value?: string | PromiseLike<string>) =>void;
publicgetPromise(): Promise<string> {
if (!this.promise) {
this.promise = newPromise((newResolver) => { this.resolver = newResolver; });
}
returnthis.promise;
}
publicsetPromise(value: string) {
if(this.resolver) {
this.resolver(value);
this.promise = null;
this.resolver = null;
}
}
}
exportclassUseThePromise {
publicconstructor(private promiseParty: PromiseParty
){
this.init();
}
privateasyncinit(){
constsubscribe = () => {
const result = awaitthis.promiseParty.getPromise();
console.log(result);
subscribe(); //resubscribe!!
}
subscribe(); //To start the subscribe the first time
}
}
exportclassFeedThePromise {
publicconstructor(private promiseParty: PromiseParty
){
setTimeout(() => {
this.promiseParty.setPromise("Hello");
}, 1000);
setTimeout(() => {
this.promiseParty.setPromise("Hello again!");
}, 2000);
setTimeout(() => {
this.promiseParty.setPromise("Hello again and again!");
}, 3000);
}
}
Post a Comment for "How To Resolve A Promise Multiple Times?"