Reputation: 1745
I have an endpoint where I make multiple of the same call but with different id in the URL. It seems to be executing API calls however it is not triggering my alert notification.
How can I correctly handle this in case it fails? Is there a cleaner/more efficient approach?
let myArray = [1,2,3,4]
myArray.forEach(i => {
let update = request.update(`view/${i}`);
return update;
});
if(update)
{
alert("Success")
} else {
alert("failed")
}
Upvotes: 0
Views: 751
Reputation: 508
A way of dealing with a Promise is to use the .then()
function which will execute callback functions to deal with the result of each of your requests.
You should use this fonction like this :
//promise.then(onFulfilled[, onRejected]);
let myArray = [1,2,3,4]
myArray.forEach(i => {
request.update(`view/${i}`).then(response => {
//Fulfilment
},reason=>{
//Rejection
});
});
This should be enough for your problem. Sometimes I prefer keeping it "simple" by managing the result of the promise in the first callback only, this implies you have control of the response you are receiving and can identify rejection other way :
let myArray = [1,2,3,4]
myArray.forEach(i => {
request.update(`view/${i}`).then(response=>{
if(response){
//If I control the response I can identify the status of the request
const data = JSON.parse(response);
switch(data.status){
case "error":
//Do stuff
break;
case "unknown":
//Do stuff
break;
case "valid":
//Do stuff
break;
}
}else{
//This means no response was received, it is different from Promise rejection
//it may have been caused by network issues.
//You can trigger some error from here or do what you want
}
});
//This way I treat the Promise in one callback instead of two
});
Documentation for .then() is available here. Hope it helped someone.
Upvotes: 0
Reputation: 4810
Assuming request.update()
is returning a Promise, you can use Promises.all(). You should read the docs to understand the behavior of this. If even one request fails, your function will fail, even if the other requests successfully updated.
//
let myArray = [1,2,3,4]
//a place to store the promises while we wait
let requests = [];
//
myArray.forEach(i => {
//save the promise in the array
requests.push( request.update(`view/${i}`) );
});
//wait for all requests to finish
Promise.all( requests )
.then(results => alert('Success'))
.catch(e => alert("failed"));
Upvotes: 1