In a ReactNative ponent, when I press a button I got the "Possible Unhandled Promise Rejection" error when I execute this function:
async onAdd(item) {
try {
const response = await fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
event_id: item.id,
event_type: item.event_type,
})
});
const responseJson = await response.json();
} catch (error) {
error(error);
}
}
I do not know why since its in a try / catch block.
UPDATED
This is the error function:
function error(value) {
if (console) {
console.error(value)
}
}
In a ReactNative ponent, when I press a button I got the "Possible Unhandled Promise Rejection" error when I execute this function:
async onAdd(item) {
try {
const response = await fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
event_id: item.id,
event_type: item.event_type,
})
});
const responseJson = await response.json();
} catch (error) {
error(error);
}
}
I do not know why since its in a try / catch block.
UPDATED
This is the error function:
function error(value) {
if (console) {
console.error(value)
}
}
Share
Improve this question
edited Mar 24, 2018 at 20:51
Giao M
asked Mar 24, 2018 at 20:40
Giao MGiao M
4,7258 gold badges31 silver badges68 bronze badges
4
-
Well
error(error)
is most likely throwing an exception, aserror
is not a function. – Bergi Commented Mar 24, 2018 at 20:49 - What is your 'error()' method doing? If it throws an error, so will onAdd. – Holy Joe Commented Mar 24, 2018 at 20:49
- Possible duplicate of stackoverflow./questions/38842499/… – Bruno Mazzardo Commented Mar 24, 2018 at 20:55
-
Is your code supposed to do something with
responseJson
? Like return it? – jfriend00 Commented Mar 25, 2018 at 0:30
2 Answers
Reset to default 4The problem is you are redefining the symbol error
here with the catch
argument:
} catch (error) {
error(error);
}
so that hides your error()
function. Change to this (with different names for the two symbols):
} catch (err) {
error(err);
}
So, when you try to call error(error)
you're trying to execute a non-function which throws which causes onAdd()
to reject the promise that the async function returns and you don't have a .catch()
handler on that function call (because you didn't think it could reject). And, as long as your catch()
handler is written so that it doesn't throw itself, then your promise won't reject, but your coding error was causing it to throw.
The method that calls this function should handle the error too, probably on your React Class