Reputation: 9025
I have a function 'open' that I want to return a promise to the calling method, so that in my close function I resolve the Promise
open(config){
this.closePromise = new Promise()
return this.closePromise
}
close(closeArgs){
this.closePromise.resolve(closeArgs)
...
}
... so that my calling method gets a callback when my 'close' function is called like this :
myService.open(myData)
.then( closeArgs => console.log('closed'))
I am getting errors like 'Promise resolver undefined is not a function' I am looking at the docs here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve but nothing seems to fit my needs. ( Im starting to wonder if I should just use an Observable in this scenario, as it may fit my situation better ).
Is this a bad scenario to be using a Promise or am I just doing it wrong ? Thanks
Upvotes: 0
Views: 250
Reputation: 664936
A promise does not have a resolve
method. You need to pass an executor callback to the new Promise
constructor to gain access to the resolving function:
open(config) {
return new Promise(resolve => {
if (this.onClose) throw new Error("not yet closed, cannot open (again)");
this.onClose = resolve;
});
}
close(closeArgs) {
if (!this.onClose) throw new Error("not yet opened, cannot close (again)")
this.onClose(closeArgs);
this.onClose = null;
}
Upvotes: 1