Is it possible to save the resolve function of a Promise outside of the executor function, i.e. in a class variable so that it could be triggered by other ongoing routines like other methods?
Something like that:
class Foo {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
});
doSomething();
}
doSomething() {
//...
this.resolve();
}
}
Update: the larger context
The upper code is just pseudo-code to show what I mean. I'm working on a React application and therefore my code is not pure JavaScript but TypeScript.
In the class where I try to do this Promise trick, let's call it AppHelper, there are two important methods:
initAppInfostarts a Promise to get it's own version number (which actually calls a Capacitor API - or if it fails (i.e. when running in Browser) it falls back to read that info frommanifest.jsonusing fetch - which is a nested Promise)didUpdateAppwhich can be called by other React components and should return, whether the app's version number changed in contrast to the last session. Because we're talking async, of course it does not simply return a boolean.- I thought about returning a Promise, which itself does not execute anything, because the relevant task is already running.
- An alternative I could think about is to accept callbacks as a parameter to this method and collect them in an array for later execution. But I thought it would be nice to have the widely known Promise API and Promises are especially nice due to the fact, that a later initialized component can attach another
.then()even if the Promise has already finished and it's still getting executed.
Do you have better ideas which approach could solve that elegantly?
(The real code does many more things and I would have to paste at least two files and explain more about the whole structure, Capacitor, Ionic, etc. that's why I tried to explain it more detailed for now. But if you think it's still necessary/helpful to see it, I will add it in another update to my post.)