I am getting this error while trying to store data in AsyncStorage in react native and the data are also not getting added to the storage
Possible Unhandled Promise
Rejection (id: 0): Error: com.facebook.react.bridge.ReadableNativeMap
cannot be cast to java.lang.String Error:
com.facebook.react.bridge.ReadableNativeMap cannot be cast to
java.lang.String*
My code is like this
//Public methods
static addProduct(id,name,qnty){
let product={
id:id,
name:name,
qty:qnty,
};
let cartResponse={};
product.rowId = this.generateHash(hashItem);
AsyncStorage.getItem('CART').then((data) => {
//Check if the product already in the cartTotalItem
if (data !== null && data.length>0) {
if (this.checkIfExist(product.rowId)) {
//Update product quantity
data[product.rowId]['qty'] += product.qty;
}else{
//Add add product to the storage
data[product.rowId] = product;
}
//Update storage with new data
AsyncStorage.setItem("CART", data);
cartResponse = data;
}else{
let cartItem ={};
cartItem[product.rowId] =product;
AsyncStorage.setItem("CART", cartItem);
cartResponse =cartItem;
}
return true;
}).catch(error => {
console.log("Getting cart data error",error);
return false;
});
}
I tried to look for solution and i found few links out of which this,
Possible Unhandled Promise Rejection (id:0) Warning kinda old, but has same problem as me.
I tried to apply the same solution from the thread but that did not fix the issue.
Can anyone please help? ? Thank you.
The error is caused by setItem function. setItem is also returns a promise and your value should be a string.
Sample
AsyncStorage.setItem("CART", JSON.stringify(cartItem));
The promise chain can be confusing. The underlying problem is that the internal Promise rejection isn't chained to the external Promise.
const test = flag => {
return Promise.resolve('Happy')
.then(msg => {
if (flag === 0) return msg;
if (flag === 1) return Promise.reject('Kaboom!');
if (flag === 2) Promise.reject('Crash!');
})
.catch(err => {
return `Error: ${err}`;
});
};
test(0).then(res => log(res)); //'Happy'
test(1).then(res => log(res)); //'Error: Kaboom!'
test(2).then(res => log(res)); //'undefined' then UnhandledPromiseRejectionWarning
In the examples above, (0) exits without error, (1) rejects in a chained way by returning the inner Promise, (2) exits without error but then shows the annoying warning.
So the problem block in the original code should be:
if (data !== null && data.length>0) {
if (this.checkIfExist(product.rowId)) {
//Update product quantity
data[product.rowId]['qty'] += product.qty;
} else {
//Add add product to the storage
data[product.rowId] = product;
}
//Update storage with new data
cartResponse = data;
return AsyncStorage.setItem("CART", data); //chain the promises
} else {
let cartItem ={};
cartItem[product.rowId] =product;
cartResponse =cartItem;
return AsyncStorage.setItem("CART", cartItem); //chain the promises
}
By returning the AsyncStorage.setItem(...) result the outer catch can handle the error.
I realise this is an old post, but this issue confused me in the past. Hopefully this will clarify things for others.
Related
I have a scenario where I am returning a promise.
The promise is basically triggered by an ajax request.
On rejecting the promise it shows an error dialog that there is a server error.
What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.
My code looks something like this:
function makeRequest(ur, params) {
return new Promise(function (resolve, reject) {
fetch(url, params).then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
});
} else {
if (status === 401) {
redirectToLoginPage();
} else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
reject({ status, error });
});
}
}
});
});
}
As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.
Is this code OK, or is there any better way to accomplish this?
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object. The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.
The real consequence here is what does that mean to the consumer of the promise if its state is never changed? Any .then() or .catch() listeners for resolve or reject transitions will never get called. Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place). If they don't, then that code generally never gets to finish its work.
Or if code is using await on the promise instead of .then(), then that function will just remain suspended forever on that await. The rest of the function will be dead code and will never execute.
It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing. There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.
As you can see if the status is 401, I am redirecting to login page.
Promise is neither resolved nor rejected.
Is this code OK? Or is there any better way to accomplish this.
In this particular case, it's all OK and a redirect is a somewhat special and unique case. A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved. The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.
I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.
However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:
You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.
Here's an example (I think this should work for your business logic, not 100% sure):
const constants = {
SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
// fetch already returns a Promise itself
return fetch(url,params)
.then((response) => {
let status = response.status;
// If status is forbidden, redirect to Login & return nothing,
// indicating the end of the Promise chain
if(status === 401) {
redirectToLoginPage();
return;
}
// If status is success, return a JSON Promise
if(status >= 200 && status < 300) {
return response.json();
}
// If status is a failure, get the JSON Promise,
// map the message & status, then Reject the promise
return response.json()
.then(json => {
if (!json.message) {
json.message = constants.SERVER_ERROR;
}
return Promise.reject({status, error: json.message});
})
});
}
// This can now be used as:
makeRequest("http://example", {})
.then(json => {
if(typeof json === "undefined") {
// Redirect request occurred
}
console.log("Success:", json);
})
.catch(error => {
console.log("Error:", error.status, error.message);
})
By contrast, calling your code using:
makeRequest("http://example", {})
.then(info => console.log("info", info))
.catch(err => console.log("error", err));
Will not log anything because the call to http://example will fail, but the catch handler will never execute.
As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:
function makeRequest(ur,params) {
return new Promise(function(resolve,reject) {
fetch(url,params)
.then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
})
}
else {
reject(response);
}
})
});
}
makeRequest().then(function success(data) {
//...
}, function error(response) {
if (response.status === 401) {
redirectToLoginPage();
}
else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
//do sth. with error
});
}
});
That means I would reject every bad response state and then handle this in your error handler of your makeRequest.
It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.
Instead, you could defer the promise, or (in this case) reject with status code/error.
The ECMAScript spec explains the purpose of promises and new Promise():
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
25.6.3.1 Promise ( executor )
NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.
You should use promises to obtain future values. Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.
Since you’ve also mixed program control flow (redirection logic) into your promise’s “executor” logic, your promise is no longer “a placeholder for the results of a computation;” rather, it’s now a little JavaScript program masquerading as a promise.
So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:
async function makeRequest(url, params) {
let response = await fetch(url, params);
let { status } = response;
if (status >= 200 && status < 300) {
let data = await response.json();
successLogic(data);
} else if (status === 401) {
redirectToLoginPage();
} else {
let error = await response.json()
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
errorLogic({ status, error });
}
}
I think that I am not understanding something properly here as it's very strange behaviour. If I call queryFindPlayer it should be falling into the .then which it does if queryFindContract function is not there but when it is there like below it seems to fall to the queryFindPlayer catch and add a new player.
queryFindPlayer(models, ConsoleId, UserId, SeasonId, LeagueId).then(players => {
const player = players[0];
queryFindContract(db, player.Team.id, UserId, SeasonId, LeagueId).then(contracts => {
console.log("player has a contract to a team");
}).catch(e => {
console.log("failed to find player");
});
}).catch(e => {
queryAddPlayer(models, UserId, TeamId).then(player => {
console.log("added player");
}).catch(addPlayerError => {
console.log("failed to add player, shouldn't happen");
});
});
If queryfindPlayer() resolves so you start execution of the .then() handler, but then you end up in the queryFindPlayer().catch() handler, that can occur for one of the following reasons:
If your code threw an exception before calling queryFindContract() such as if const player = players[0] threw an error of if queryFindContract() wasn't defined.
If your code threw an exception evaluating the arguments to pass queryFindContract() such as player.Team.id throws or any of the other variables you're passing don't exist.
If queryFindContract() throws synchronously before it returns its promise.
If queryFindContract() doesn't return a promise and thus queryfindContract().then() would throw an exception.
All of these will cause a synchronous exception to be thrown in the queryFindPlayer.then() handler which will cause it to go to the queryFindPlayer.catch() handler. It never gets to the queryFindContract().catch() handler because queryFindContract() either never got to execute or because it never got to finish and return its promise.
You can most likely see exactly what is causing your situation by just adding
console.log(e)
at the start of both .catch() handlers. For clarity, also add a descriptive string before the e. such as:
console.log("qfc", e);
and
console.log("qfp", e);
I pretty much always log rejections, even if expecting them sometimes because you can also get rejections for unexpected reasons such as programming errors and you want to be able to see those immediately and not get confused by them.
Thanks for the help, I was not using the exception handler how intended.
queryGetContractById(models, id).then(c => {
return queryFindPlayer(models, ConsoleId, UserId, SeasonId, LeagueId).then(players => {
if(players.length != 0) {
return queryFindContract(models, players[0].Team.id, UserId, SeasonId, LeagueId).then(contracts => {
if(contracts.length != 0) {
console.log("player has a contract to a team");
} else {
queryUpdatePlayersTeam(models, players[0].id, TeamId);
}
});
} else {
return queryAddPlayer(models, UserId, TeamId).then(player => {
console.log("added player");
});
}
});
}).catch(e => {
console.log("failed", e);
});
In my promise, I rejected if there was no data returned and resolving if there was. I can see how this was wrong and I think this is now right.
I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:
const isbn = require('node-isbn');
var books = []; // assume this is filled in elsewhere
books.forEach(function(item) {
if (item.publication_year == '' ||
item.num_pages == '') {
isbn.provider(['openlibrary', 'google'])
.resolve(item.isbn)
.then(function (book) {
item.num_pages = book.pageCount;
item.publication_year = book.publishedDate.replace( /^\D+/g, '');
}).catch(function (err) {
console.log('Book not found', err);
});
}
console.log(item)
});
However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?
Try not to use Promise inside forEach
Put your console.log inside the then block , it will print the result for you.You are doing a asynchronous operation by resolving promise so it will take some time for the data to come back , however since your console.log is outside of that promise , that will get executed first.
So if you want to see those values, you should put your console.log inside your then block.
However, You can use await and for of syntax to achieve the result
for await (item of books) {
if (item.publication_year == '' || item.num_pages == '') {
const book = await isbn.provider(['openlibrary', 'google'])
.resolve(item.isbn);
item.num_pages = book.pageCount;
item.publication_year = book.publishedDate.replace( /^\D+/g,'');
}
console.log(item)
}
console.log(books)
I am starting to use the async await pattern more over the standard Promise syntax, as it can keep the code flatter. I have played and experimented with them a bit and thought I understood how to use them.
That has now come crumbling down!
I have a function that returns a Promise...
private async checkSecurityTokenForNearExpiry(): Promise<boolean> {
const expiryOffset = 10;
try {
let existingToken = await this.userAuthorisationService.getSecurityToken();
if (existingToken != null && !existingToken.isTokenExpired(expiryOffset)) {
return true;
}
// Attempt to get a new token.
this.logger.debug('checkSecurityTokenForNearExpiry requesting new token.');
this.getSecurityTokenWithRefreshToken().subscribe(obs => {
return true;
},
error => {
// All errors already logged
return false;
});
} catch (error) {
this.logger.error(`checkSecurityToken ${error}`);
return false;
}
}
This happens to call other function that returns a promise and also has on Observable, but all this seems to be ok.
I then call this function as follows...
this.getDataStoreValues().then(async () => {
await this.checkSecurityTokenForNearExpiry(); // <-- not waiting
requestData(); // <-- this is called before checkSecurityTokenForNearExpiry returns
...
This is inside another Promise then callback marked as async, (which should be ok?), but to my alarm the call to this.checkSecurityTokenForNearExpiry() is not finished before I see the requestData() being called. I don't need the boolean result of checkSecurityTokenForNearExpiry but added this just to see if returning something would make s difference, but it didn't.
I am lost here!
Does anyone know what I am missing here?
Thanks in advance!
async/await are working as expected but there are two factors that prevent your code from working correctly.
Observables have no special interaction with async functions. This means that they are fire and forget just as they are in normal functions. You are not awaiting getSecurityTokenWithRefreshToken but even if you did await it, it would still not behave as you want because the result would actually be the subscription returned by the call to subscribe wrapped in a Promise.
The callbacks taken as arguments by subscribe are not intended to return values so returning from them has no effect as Observable implementations will not propagate their results.
In order to make this work you need to convert the Observable into a Promise as follows
async checkSecurityTokenForNearExpiry(): Promise<boolean> {
const expiryOffset = 10;
try {
let existingToken = await this.userAuthorisationService().getSecurityToken();
if (existingToken != null && !existingToken.isTokenExpired(expiryOffset)) {
return true;
}
// Attempt to get a new token.
this.logger.debug('checkSecurityTokenForNearExpiry requesting new token.');
try {
await this.getSecurityTokenWithRefreshToken().toPromise();
return true;
} catch (error) {
return false;
}
} catch (error) {
this.logger.error(`checkSecurityToken ${error}`);
return false;
}
}
Note, if you are using RxJS you may need to add the following import
import 'rxjs/add/operator/toPromise';
I have a scenario where I am returning a promise.
The promise is basically triggered by an ajax request.
On rejecting the promise it shows an error dialog that there is a server error.
What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.
My code looks something like this:
function makeRequest(ur, params) {
return new Promise(function (resolve, reject) {
fetch(url, params).then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
});
} else {
if (status === 401) {
redirectToLoginPage();
} else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
reject({ status, error });
});
}
}
});
});
}
As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.
Is this code OK, or is there any better way to accomplish this?
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object. The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.
The real consequence here is what does that mean to the consumer of the promise if its state is never changed? Any .then() or .catch() listeners for resolve or reject transitions will never get called. Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place). If they don't, then that code generally never gets to finish its work.
Or if code is using await on the promise instead of .then(), then that function will just remain suspended forever on that await. The rest of the function will be dead code and will never execute.
It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing. There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.
As you can see if the status is 401, I am redirecting to login page.
Promise is neither resolved nor rejected.
Is this code OK? Or is there any better way to accomplish this.
In this particular case, it's all OK and a redirect is a somewhat special and unique case. A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved. The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.
I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.
However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:
You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.
Here's an example (I think this should work for your business logic, not 100% sure):
const constants = {
SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
// fetch already returns a Promise itself
return fetch(url,params)
.then((response) => {
let status = response.status;
// If status is forbidden, redirect to Login & return nothing,
// indicating the end of the Promise chain
if(status === 401) {
redirectToLoginPage();
return;
}
// If status is success, return a JSON Promise
if(status >= 200 && status < 300) {
return response.json();
}
// If status is a failure, get the JSON Promise,
// map the message & status, then Reject the promise
return response.json()
.then(json => {
if (!json.message) {
json.message = constants.SERVER_ERROR;
}
return Promise.reject({status, error: json.message});
})
});
}
// This can now be used as:
makeRequest("http://example", {})
.then(json => {
if(typeof json === "undefined") {
// Redirect request occurred
}
console.log("Success:", json);
})
.catch(error => {
console.log("Error:", error.status, error.message);
})
By contrast, calling your code using:
makeRequest("http://example", {})
.then(info => console.log("info", info))
.catch(err => console.log("error", err));
Will not log anything because the call to http://example will fail, but the catch handler will never execute.
As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:
function makeRequest(ur,params) {
return new Promise(function(resolve,reject) {
fetch(url,params)
.then((response) => {
let status = response.status;
if (status >= 200 && status < 300) {
response.json().then((data) => {
resolve(data);
})
}
else {
reject(response);
}
})
});
}
makeRequest().then(function success(data) {
//...
}, function error(response) {
if (response.status === 401) {
redirectToLoginPage();
}
else {
response.json().then((error) => {
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
//do sth. with error
});
}
});
That means I would reject every bad response state and then handle this in your error handler of your makeRequest.
It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.
Instead, you could defer the promise, or (in this case) reject with status code/error.
The ECMAScript spec explains the purpose of promises and new Promise():
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
25.6.3.1 Promise ( executor )
NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.
You should use promises to obtain future values. Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.
Since you’ve also mixed program control flow (redirection logic) into your promise’s “executor” logic, your promise is no longer “a placeholder for the results of a computation;” rather, it’s now a little JavaScript program masquerading as a promise.
So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:
async function makeRequest(url, params) {
let response = await fetch(url, params);
let { status } = response;
if (status >= 200 && status < 300) {
let data = await response.json();
successLogic(data);
} else if (status === 401) {
redirectToLoginPage();
} else {
let error = await response.json()
if (!error.message) {
error.message = constants.SERVER_ERROR;
}
errorLogic({ status, error });
}
}