我有一个科尔多瓦移动应用程序,将离线数据存储在localStorage中。最近用户开始收到QUOTA_EXCEEDED_ERR错误,因为localStorage有5MB的限制。我决定使用"localForage“框架,但我注意到它是异步工作的。因为我不想重写所有复杂的应用程序包装到回调函数中,所以我想知道是否有什么方法可以同步使用"localForage“(等到getItem函数返回值)。
下面是我想要做的代码示例:
localforage.setItem('testKey', 'testValue', function() {
var value = getValue('testKey');
console.log(value); // here I get undefined, but I want to get a value
});
function getValue(key) { // I want this function to return value
var result;
localforage.getItem(key, function(value) {
result = value;
});
return result;
}我希望getValue()在不更改任何其他代码的情况下返回值
发布于 2019-02-07 17:02:28
根据这个link
localForage有一个双重接口,允许您使用Node式回调或Promise。如果您不确定哪一个适合您,建议您使用Promises。
因此,如果您愿意,您可以使用它们中的任何一个。如果使用promises,您可以使用async/await等待结果
localforage.setItem('testKey', 'testValue', async function() {
var value = await getValue('testKey')
console.log(value); // here I get undefined, but I want to get a value
});
async function getValue(key) {
var result = await localforage.getItem(key);
return result;
}发布于 2020-04-13 15:36:11
localforage.setItem('testKey', 'testValue', async function() {//declare function as async
var value = await getValue('testKey'); //wait for the value
console.log(value); // "testValue" value should show in console
});
//declare function as async
async function getValue(key) {
var result = await localforage.getItem(key); //wait for the localforage item
return result;
}JSFiddle地址:https://jsfiddle.net/mvdgxorL/
发布于 2020-08-29 20:13:19
https://localforage.github.io/localForage/#data-api-getitem,使用async/await
try {
const value = await localforage.getItem('somekey');
// This code runs once the value has been loaded
// from the offline store.
console.log(value);
} catch (err) {
// This code runs if there were any errors.
console.log(err);
}https://stackoverflow.com/questions/54569232
复制相似问题