My problem
I have an asynchronous method populate() that tries to do something, and if it fails, catches the error and calls another asynchronous method populateFromServer() (which can fail too).
I call the first in a Promise.all() with a catch afterwards in case no attempt worked. However, .all() always trigger because of populate(), for some reason, although it should be caught.
Here is a simplified version of my code (typescript):
abstract class Database {
public static async populate() {
try {
await populateFromLocalFile();
} catch (err) {
await this.populateFromServer();
}
}
private static async populateFromServer() {
await fetchFromServer(); // Might fail eg. if there is no internet
}
}
And somewhere else:
Promise.all([
ChildDB1.populate(),
ChildDB2.populate(),
ChildDB3.populate(),
])
.then(() => /* population worked (either local or distant) */)
.catch(() => /* no population attempt worked */)
My code seems to get caught after the Promise.all when populate() fails, even though I caught it and populateFromServer() worked perfectly fine (I checked with logs). Why? How can I fix that?
What I tried
Returning Promise.resolve()
Someone suggested to return Promise.resolve() at the end of the catch block, but it doesn't fix the problem:
public static async populate() {
try {
await populateFromLocalFile();
} catch (err) {
await this.populateFromServer();
return Promise.resolve()
}
return Promise.resolve()
}
Using .then
I also tried using the other way with .then but I still have that problem
abstract class Database {
public static async populate() {
await populateFromLocalFile()
.then(() => doStuff())
.catch(async () => {
console.log('error happened here');
await this.populateFromServer();
});
}
private static async B() {
await fetchFromServer();
}
}