Reputation: 199
I'm struggling to handle errors with Promise.all:
return Promise.all([
this.pagination(),
this.prepareParams(this.params, this.requestData),
this.fetchRecipes(this.apiData, this.params)
])
.catch(e => console.log());
Firstly I've just tried to throw an exception in this.pagination()
, it was even handled, but strangely enough the next Promises were despite executed.
pagination(): Promise<any> {
return new Promise(resolve => {
if(...) {
...
resolve();
} else {
...
throw "no more results";
}
}
Then I tried to use Promise.reject("no more results")
instead, but the problem is that it ignores now somehow my catch
Uncaught (in promise): no more results
Just to clarify for others: My original intention was to prevent the execution of the next 2 Promises, if the first one was rejected. Mistakenly I assumed that Promise.all
fulfills this requirement. Thanks to the answer of traktor53 I realised that chaining promises is a better solution.
Upvotes: 0
Views: 1007
Reputation: 367
Better to add try - catch block when you call a function
else
pagination(): Promise<any> {
return new Promise((resolve, reject) => {
if(...) {
...
resolve();
} else {
...
reject("no more results");
}
}
In your function call.
pagination().then(err, value) {}
Upvotes: 0
Reputation: 19301
Promise.all
waits for all the promises in its argument array to be fulfilled before returning an array of results, but will reject the promise it returned as soon as any of the promises in the array become rejected ("fast rejection").
Promise.all
calls then
on each of the promises passed to obtain its fulfilled value or rejected reason. It does not attempt to abort other promises if one of them is rejected - there is no mechanism in Promise standards to cancel a promised operation.
If you want to continue execution of promise operations only after a preceding promise is successful, use chaining rather than promise.all
, taking care that the this
value is correct in promise call backs (e.g. by using arrow functions):
function objectMethod () {
return this.pagination()
.then( data=>this.prepareParams(this.params, this.requestData))
.then( data=>this.fetchRecipes(this.apiData, this.params));
}
// catch errors encountered during call:
someObject.someMethod().catch(e => console.log(e));
Upvotes: 2
Reputation: 455
The callback parameter to the Promise
constructor (MDN) takes two arguments, idomatically called resolve
and reject
, the latter of which you are missing. Instead of throwing the error, you must pass it to reject
. Therefore:
pagination(): Promise<any> {
return new Promise((resolve, reject) => {
if(...) {
...
resolve();
} else {
...
reject("no more results");
}
}
Upvotes: 0