我如何在localStorage中分配localForage中的变量?

编程入门 行业动态 更新时间:2024-10-22 23:40:47
本文介绍了我如何在localStorage中分配localForage中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请帮我解决以下问题。

Please help me with the following.

我一直在将我的AngularJS应用程序从localStorage转换为localForage。

I have been converting my AngularJS application from localStorage to localForage.

在我的应用程序中我分配了localStorage像这样的价值。

throughout my application I was assigning the localStorage value like this.

window.localStorage.setItem('localSavedValue','SavedValue');

然后我正在检索这样的数据,

and then I was retrieving the data like this,

var myValue = window.localStorage.getItem('localSavedValue');

所以当我在console.log(myValue)时; //输出'SavedValue'

So when I console.log(myValue); // it outputted 'SavedValue'

我尝试使用localForage时似乎无法做到这一点,

I cannot seem to do this with localForage when I try,

$localForage.setItem('localSavedValue','SavedValue'); var myValue = $localForage.getItem('localSavedValue'); console.log(myValue); // returns an object.

我没有将值设置为myValue。

I don't get the value set to myValue.

我确信这是与promises有关的事情,因为当我使用回调时我可以访问正确的'myValue'但是我想把它从调用中取出来用于其余的服务。

I am sure this is something do do with promises as when I use the callback I can access the correct 'myValue' however I want to get it out of the call back to use in the rest of the service.

另外要注意,我在服务中因此无法分配到$ scope(除非我不知道如何)。

Also to note, I am in a service so can't assign to $scope (unless I don't know how).

感谢任何帮助。

谢谢 B

推荐答案

LocalForage在设计上是异步的,所以我建议你使用像@RouR建议的Promise。

LocalForage is async by design so I would suggest you to use Promises like @RouR suggested.

代码清晰度的一个小改进是链 - 返回promise结果,但你仍然无法避免异步代码的后果。

A minor improvement for code clarity would be to chain-return the promise results, but you still can't avoid the async code consequences.

$localForage.setItem('localSavedValue','SavedValue').then(function() { return $localForage.getItem('localSavedValue'); }).then(function(data) { console.log('I\'m printed second', data); }); console.log('I\'m printed first');

如果您使用的是Babel,这种迁移的更友好方法是将其配置为使用 transform-async-to-generator 或 preset-es2017 并重写代码为

If you are using Babel, a more friendly approach for such migrations would be to configure it to use transform-async-to-generator or preset-es2017 and rewrite such code as

await $localForage.setItem('localSavedValue','SavedValue'); const data = await $localForage.getItem('localSavedValue'); console.log(data);

更多推荐

我如何在localStorage中分配localForage中的变量?

本文发布于:2023-10-27 03:22:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   分配   如何在   localStorage   localForage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!