简体   繁体   中英

Promises in AsyncStorage from React Native

Wrinting a lttle wrapper around AsyncStorage from React Native, i have a little problem with the getAllKeys function.

What is wrong in this snipped, if i want retrive all the 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 very much

You are returning items synchronously, however .getAllKeys and .getItems return Promises, so are highly likely to be asynchronous

Using Promise.all to wait for all AsyncStorage.getItem to complete, your code can be written as follows

getAll: () => 
    Promise.all(AsyncStorage.getAllKeys()
        .then(ks => 
            ks.map(k => 
                AsyncStorage.getItem(k)
            )
        )
    )
,

usage:

.getAll()
.then(items => 
    // do something with items 
)
.catch(err => 
    // handle errors
);

to explain the error in the comment - if you use {} in an arrow function, you must use return to return a 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);
    })
})),

You need to :

  • form an array of the promises returned by AsyncStorage getItem(k) ,
  • use Parse.Promise.when() (or Promise.all() ) to aggregate the array of promises,
  • return a promise from getAll() .
getAll: function() {
    var items = ["hh"];
    return AsyncStorage.getAllKeys().then(ks => {
        return Parse.Promise.when(ks.map(k => AsyncStorage.getItem(k))).then(results => items.concat(results));
    });
},

If "hh" is just there for debug purposes, simplify to :

getAll: function() {
    return AsyncStorage.getAllKeys().then(ks => {
        return Parse.Promise.when(ks.map(k => AsyncStorage.getItem(k)));
    });
},

In either case, call as follows :

foo.getAll().then(function(results) {
    // here, `results` is an array of values promised by multiple calls to `AsyncStorage.getItem(k)`
    console.log(results);
}, function(error) {
    // here, handle whatever error condition that might have arisen
    console.log(error);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM