How to send proper response from Promise - javascript

I have axios to get data from Server in CustomerService.js
UpdateCustomer(customer){
let vm = this;
return new Promise((resolve, reject) => {
Axios.post("/members/update", customer)
.then(function (response) {
if (!response.success){
reject(response.message);
}else{
resolve(vm.CommonService.parseJson(response.data));
}
})
.catch(function (error) {
reject(error);
});
});
}
In my vue component file I am receving this rsponse but problem I am getting response in both then and catch and it throws error.
vm.CustomerService.UpdateCustomer({customer})
.then(function (data) {
vm.app.Success("Success");
vm.postCustomerTask(data);
})
.catch(function (error) {
vm.app.Fail(error);
});
I am getting Json parse error. I dont seem to find exact problem. All I can think of is reject from UpdateCustomer is going in then in vue component.

I think you have wrong logic in the if-else statements. You have rejected under the success logic.
if (response.success){
resolve(vm.CommonService.parseJson(response.data));
} else {
reject(response.message);
}

Related

how to handle if ip or domain are wrong in fetch in javascript

when ip or domain is wrong in request using fetch in javascript is there any solution ? to handle stop request if ip or domain is provided wrong.
var ip_or_domain=192.168.1.1
fetch(ip_or_domain+'/something-get-api')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
If there's an error, you can catch it:
fetch(ip_or_domain+'/something-get-api')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
})
.catch(function(error) {
console.log(error);
});
Unless you have some way to validate the values the only other way to know if it is valid or not is to actually make the request
You need to implement error handling yourself. Start by checking response.ok and throw an error if it is false then use catch() for errors.
You can also check response.status for more granular errors
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
console.log(JSON.stringify(myJson));
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
var ip_wishlist = ['192.168.1.1', '192.168.1.2'];
// where you can keep the ip_wishlist dynamically in a global array.
if(ip_wishlist.indexOf(ip_or_domain) !== -1){
fetch(ip_or_domain+'/something-get-api')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
})
.catch(function(error) {
console.log(error);
});
}

Catch error in promise from a service in an Angular component

Hi everyone running into a problem with a post service I created in angular. Struggling to catch the error from my component when I call the service. I was able to catch the error from the service but I need to do this from my component to properly handle the error. Any advice would be greatly appreciated.
Service
sendData(obj) {
let promise = new Promise((resolve) => {
this.http.post(this.URL, obj, this.httpOptions)
.toPromise()
.then(
res => {
console.log(res);
resolve(res);
}
)
//.catch((err) => {
// console.log(err);
// throw err;
//});
});
return promise;
}
Component
this._myservice.sendData(this.myobj)
.then(function (res) {
console.log('data sent');
})
.catch(error => {
console.warn('from component:', error);
// this console warn never gets logged out
});
Do I need to update something in my service to allow me to catch the error from the component?
You're creating your own Promise here, but you never call reject if the Promise you're wrapping rejects (throws an error). This is known as the the new Promise antipattern. In your case, you can simply remove this wrapper and replace the call to resolve with a return in order to achieve what you need, like so:
sendData(obj) {
return this.http.post(this.URL, obj, this.httpOptions)
.toPromise()
.then(res => {
console.log(res);
return res;
});
}
In order to provide more context, you could fix your original problem by calling reject. This would look like this:
// DONT'T DO THIS
sendData(obj) {
let promise = new Promise((resolve, reject) => {
this.http.post(this.URL, obj, this.httpOptions)
.toPromise()
.then(res => {
console.log(res);
resolve(res);
})
.catch((err) => {
console.log(err);
reject(err); // Here.
});
});
return promise;
}
But, as I said above, this is overcomplicated and unnecessary. I hope that it demonstrates how the Promise your component has access to could never see errors that occurred in the HTTP call.

call the same http request if it fails but with different parameter to get default data

does it make sense to call the same http request call within the catch if the first one fails but with different parameter in order to return some default data ?
var defaultData = false;
clientService.getClients(defaultData)
.then(function (res) {
//do something
}).catch(function (err) {
defaultData = true;
clientService.getClients(defaultData)
.then(function (res) {
//do something
}).catch(function (err) {
console.log(err)
});
});
or this is a bad way ?
Be sure to return the new promise to the catch handler. The code will then chain properly and it avoids nesting:
clientService.getClients({defaultData:false})
.catch(function (err) {
return clientService.getClients({defaultData: true})
}).then(function (res) {
//return something
}).catch(function (err) {
console.log(err)
//IMPORTANT re-throw err
throw err;
});
This issue not bad but I think you have to find reason of the failure and on the furniture do some action.
the best is that you have to create an error handler like:
errorHandler(error:any){
///.....
}
In this method you should check status code of response, for instance if it is 500, you can't call again. or some thing like this.

Promise All Reject Issue

I used promise all function for running multiple promises. I'm getting error Uncaught (in promise) reject, but here I've used the catch block. I don't know how this it throw the error.
function fetch(data) {
new Promise(function(resolve,reject) {
data ? reject('reject') : resolve('resolve')
})
}
Promise.all([fetch(), fetch('sssssssss')])
.then(function(data) {
console.log('all finished',data)
})
.catch(function(error) {
alert('ssssssssssssss')
})
fetch()
See below code. hope it will solve your problem.
function fetch(data) {
return new Promise(function(resolve,reject) {
data ? reject('reject') : resolve('resolve')
})
}
Promise.all([fetch(), fetch('sssssssss')])
.then(function(data) {
console.log('all finished',data)
})
.catch(function(error) {
alert('ssssssssssssss')
})
fetch()

Possible unhandled promise rejection

I'm trying to reject a promise as explained in the documentation of the API of the framework I'm using (Apollo stack) but it doesn't show an example, it only states just that I have to reject the promise if there is an error, and I'm trying to get rid of the annoying YellowBox message "Warning: Possible unhanded promise rejection" when trying my application without an internet connection.
My method actually works, it goes to the catch and it shows the error message, but i keep getting the annoying YellowBox message, that's what I'm trying to fix.
first thing I did, goes to the catch, as expected, but it shows a YellowBox message Warning: Possible unhandled promise rejection...
return client.query({ query: gql`...`, }).then((data) => {
console.log(data);
data;
}).catch((error) => {
console.log(error);
error;
});
Last thing I've tried:
var promise = new Promise(function(resolve, reject) {
//async call, client.query(..) "returns a promise that should be rejected
//if there is an error message..."
client.query({ query: gql`...`, }).then(({data}) => {
console.log(data);
resolve(data);
}).catch((error) => {
console.log(error); // goes right here, works.
reject(error.message);
});
});
//just trying this out
promise.then((data) => {
console.log(data);
}).catch((error) => {
console.log(error);
});
Also, adding the tag Meteor because couldn't find Apollo but it's pretty much the same thing.
Trying more stuff as suggested in the answers and comments:
var promise = new Promise(function(resolve, reject) {
client.query({
query: gql`...`,
}).then(({data}) => {
console.log(data);
resolve(data);
}).catch((error) => {
reject(error.message);
});
}, (error) => {
console.log(error);
});
another:
var callback = {
success: function(data) {
console.log("SUCCESS");
},
error: function(data) {
console.log("ERROR");
}
};
var promise = new Promise(function(resolve, reject) {
client.query({
query: gql`...`,
}).then(({data}) => {
console.log(data);
resolve(data);
}).catch((error) => {
console.log(error);
reject(error.message);
});
return promise;
});
promise.then(callback.success, callback.error);
another:
client.query({
query: gql`...`,
}).then(({data}) => {
console.log(data);
}, (error) => {
console.log(error);
});
ApolloStack: http://docs.apollostack.com/apollo-client/network.html it says, that returns a promise that should be rejected if an error occurs.
YellowBox detects unhandled promises and such things and throws warnings.
There's no reason to create a promise if client.query does it for you...
// no new Promise here, just make the query
return client.query({ query: gql`...`, }).then((data) => {
console.log(data);
data;
}).catch((error) => {
console.log(error);
error;
});
Found the issue, the framework is working on it at the moment, a fix will come soon, so there is no right answer for now.
I will copy-paste the right way (as shown in the question). It's also copied from the official frameworks' documentation that shows how to do it, so the next person coming with the same problem will know they will have to wait a couple of days until they fix it.
client.query({ query: gql`...`, }).then((data) => {
console.log(data);
}).catch((error) => {
console.log(error);
});
try to handle error in rejection callback instead of catch callback:
var promise = new Promise(function(resolve, reject) {
client.query({ query: gql`...`, }).then(({data}) => {
console.log(data);
resolve(data);
}, (error)=>{
console.log(error); // goes right here, works.
reject(error.message);
})
});

Categories

Resources