Promise All Reject Issue - javascript

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

Related

Javascript uncaugh error in promise even with a catch

With Javascript, I am trying to make a call to an external API when a form is submited.
I am using promises in order to set follow up actions once the call is done and to catch eventual errors.
This is where my problem is, even if I think I am catching my errors correctly, the console throws an
Uncaught (in promise) error : [The error I throw]
I do not understand why.
Here is a minimal version of my code which would reproduce the error when the refreshToken is expired :
try {
functionGeneratingTheError();
} catch (error) {
doSomethingElse();
}
function functionGeneratingTheError() {
var getTokenCallPayload = {
"client_id" : clientId,
"client_secret" : clientSecret,
"refresh_token" : refreshToken,
"grant_type" : "refresh_token"
};
var getTokenCallOptions = {
"method" : "POST",
"body" : JSON.stringify(getTokenCallPayload),
"muteHttpExceptions" : false
};
fetch(tokenURL, getTokenCallOptions)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Error");
}
})
.then(data => {
doSomething();
})
.then(response=> {
doSomethingAgain();
})
.catch(error => {
throw error;
});
}
If I understand correctly, when the fetch is a bad request, it should throw the error "Error" which should then be caught in the first catch and run the doSomethingElse() function.
However, instead of doing that, I get this error in the browser console "Uncaught (in promise) Error: Error"
What am I doing wrong ?
I have tried including the fetch in a try{}catch(){} but it doesn't change anything.
I also tried not throwing the error and directly call my doSomethingElse() function, but then the following .then fails because data is undefined.
Change your functionGeneratingTheError function to return the chained promise like below:
function functionGeneratingTheError() {
var getTokenCallPayload = {
"client_id" : clientId,
"client_secret" : clientSecret,
"refresh_token" : refreshToken,
"grant_type" : "refresh_token"
};
var getTokenCallOptions = {
"method" : "POST",
"body" : JSON.stringify(getTokenCallPayload),
"muteHttpExceptions" : false
};
return
fetch(tokenURL, getTokenCallOptions)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Error");
}
})
.then(data => {
doSomething();
})
.then(response=> {
doSomethingAgain();
})
.catch(error => {
throw error;
});
}
And then await it in your calling code by wrapping the calling code inside an async self invoking function like so:
(async function() {
try {
await functionGeneratingTheError();
} catch (error) {
doSomethingElse();
}
})();
You can read more about async/await here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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

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

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