[英]Getting actual value from react-native asyncStorage instead of promise
[英]Returning Value of a Promise - { AsyncStorage } React-Native
我试图弄清楚如何返回承诺的结果。 我一直在这里关注React Native文档AsyncStorage页面: https ://facebook.github.io/react-native/docs/asyncstorage
我正在使用文档中提供的代码段,并做了一些自己的修改,以尝试访问数据。
如您在示例中看到的,我提供了我尝试声明一个空数组,并使用AsyncStorage调用的结果填充它。
export const loadLocalData = async () => {
var itemsStoredLocally = [];
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
stores.map((result, i, store) => {
let key = store[i][0];
let value = store[i][1];
console.log("Inside the method : ", result)
itemsStoredLocally.push(result);
});
});
})
console.log("Outside the method: ", itemsStoredLocally);
return itemsStoredLocally;
}
在我的控制台中,我得到这个:
Outside the method: Array []
Inside the method : Array [
"1234",
"The data stored locally",
]
当我真正想看到的是:
Inside the method : Array [
"1234",
"The data stored locally",
]
Outside the method: Array [
"1234",
"The data stored locally",
]
据我了解,承诺已被兑现,因此我需要以某种方式处理该承诺,以等待其解决,然后再加以利用。
麻烦是,我只是不知道如何。 我在网上看到有人提到诸如Promise.resolve()之类的东西,然后使用.then()方法,但是我尝试的一切似乎都没有用。
有什么建议么? 谢谢
您不应使用回调参数。 那是因为当您不使用Promise返回值时,那只会使编码器的工作更加困难。 相反,请忽略这些回调参数,并依赖返回的Promise:
export const loadLocalData = async () => {
var itemsStoredLocally = [];
// Use await:
const keys = await AsyncStorage.getAllKeys();
const stores = await AsyncStorage.multiGet(keys);
// Use forEach, not map: map is to return a mapped array
stores.forEach(result => {
let [key, value] = result;
// Do something with key/value?
// ...
console.log("Inside the method : ", result)
});
return stores; // Just return the result
}
该函数返回一个promise,因此您需要等待它,例如, then
使用then
:
loadLocalData.then(data => console.log("Outside the method: ", data));
请注意,仅当在该函数中使用await
时,才使用async
。 因此,您的代码中已经存在一个危险信号...
试试这个
export const loadLocalData = async () => {
var itemsStoredLocally = [];
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
stores.map((result, i, store) => {
let key = store[i][0];
let value = store[i][1];
console.log("Inside the method : ", result)
itemsStoredLocally.push(result);
});
console.log("Outside the method: ", itemsStoredLocally);
return itemsStoredLocally;
});
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.