Possible unhandled promise rejection - javascript

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);
})
});

Related

Why catch invoked with success promise?

I have maybe weird things happen I send a request to an Endpoint "/Login" and it's given me the response well!
and I do my stuff, but for some reason, I see a warning that says,
Unhandled Promise Rejection / typeError: undefined is not an object
(evaluating 'error.response.data')
If anybody has an explanation for it?
Code snippet
signIn = data => {
this.setState({loading: true});
API.post('/login', data)
.then(response => {
let {
data: {
data: {
response: {token},
},
},
} = response;
this.setState({loading: false});
reactotron.log('response', response);
reactotron.log(token);
deviceStorage.saveKey('id_token', token);
})
.catch(error => {
alert('catched!!'); // it's appear :)
this.setState({error: error.response.data, loading: false});
reactotron.error(error.response.data);
});
};
=
The wrong was here in this function ~_~ !
why get me an error?
_deviceStorage.default.saveKey is not a function
import { AsyncStorage } from '#react-native-community/async-storage';
import reactotron from 'reactotron-react-native';
const deviceStorage = {
// our AsyncStorage functions will go here :)
saveItem= async(key, value)=>{
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
reactotron.log('AsyncStorage Error: ' + error.message);
}
}
};
export default deviceStorage;
error is a string representation of the error message( rejection message). But you are treating it as if it's an object when you say error.response.data
.catch(error => {
alert('catched!!'); // it's appear :)
this.setState({error: error, loading: false});
reactotron.error(error.response.data);
});
The catch could be invoked if an error is encountered in the then block. Check your then block for any possible errors. That might be the reason why catch is invoked even when the promise returned success.
const promise1 = new Promise(function(resolve, reject) {
resolve("resp");
});
promise1.then(function(resp) {
console.log(resp);
throw 'error'
}).catch(function(error) {
console.error(error);
});

Javascript not catching error using fetch

I have an authService which has the following fetch
export const handleForm = () => {
return fetch('http://localhost:5000/login')
.then(response => {
if (!response.ok) {
throw new Error("Email or password incorrect");
} else {
return response.json();
}
})
.then(json => json)
.catch(error => error);
};
I'm calling the method from my controller:
form.onsubmit = function (e) {
handleForm(e)
.then(response => {
console.log(response);
//setAuthenticatedUser(response);
// setDomUser(response.user);
})
.catch(error => {
console.log(error);
document.querySelector('#error').innerHTML = error;
})
};
I've tried a few things to get the error in my catch, in the controller
But I keep getting the response callback fired.
The error from my authService isn't being caught
I've Tried
throw new Error();
Promise.reject();
See Promise.prototype.catch():
Syntax Section
p.catch(onRejected);
[...]
The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
Using .catch(error => error) as a callback returns the exception. So it neither "throws an error" nor "returns a Promise which is itself rejected". The promise returned by it is thus resolved, not rejected.
Simply remove .catch(error => error) and it will work. And when you're at it, also remove .then(json => json) as it is useless.

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.

How to send proper response from Promise

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);
}

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()

Categories

Resources