android - Promises in AsyncStorage from React Native -
wrinting lttle wrapper around asyncstorage react native, have little problem getallkeys function.
what wrong in snipped, if want retrive values?
getall: function(){ var items = ["hh"]; asyncstorage.getallkeys() .then( ks => { ks.foreach( k => { asyncstorage.getitem(k) .then( v => items.push(v)); //console.log(k, v)); }); }); return items; }, thanks much
you returning items synchronously, .getallkeys , .getitems return promises, highly asynchronous
using promise.all wait asyncstorage.getitem complete, code can written follows
getall: () => promise.all(asyncstorage.getallkeys() .then(ks => ks.map(k => asyncstorage.getitem(k) ) ) ) , usage:
.getall() .then(items => // items ) .catch(err => // handle errors ); to explain error in comment - if use {} in arrow function, must use return return value
getall: () => promise.all(asyncstorage.getallkeys().then(ks => { console.log(ks); // return here return ks.map(k => { console.log(k); // return here return asyncstorage.getitem(k); }) })),
Comments
Post a Comment