javascript - Javascript,localForage,使用getter在对象文字之间传递数组
问题描述
我有以下对象文字,我试图在存储对象(使用 localForage)和视图对象之间传递一个 todoList 数组。
const store = {
setUpStore() {
this.todos = localforage.createInstance({
name: 'myApp',
storeName: 'todos'
});
this.completed = localforage.createInstance({
name: 'myApp',
storeName: 'completed'
});
},
// Code omitted for brevity
get todoList() {
const todoList = [];
this.todos.iterate((value, key, iterationNumber) => {
let item = {id: key, title: value.title};
if (value.prioritized === true) {
todoList.unshift(item);
} else {
todoList.push(item);
}
}).then(() => {
console.log('Got todo list');
}).catch((err) => {
console.log(`There was an error: ${err}`);
});
return todoList;
},
}
const view = {
// Code omited for brevity
displayTodos() {
todoList = store.todoList;
console.log(todoList); // This logs what appears to be an array
todoList.forEach((item) => {
// This doesn't work
console.log(item.title);
});
}
}
当我在控制台中调用 store.todoList getter 时,我得到一个可以使用的数组。view.displayTodos() 方法中的 console.log(todoList) 似乎可以工作,但在 view 方法中调用 forEach() 或对 todoList 执行任何其他类型的数组操作不起作用。这里发生了什么?
解决方案
第一种方法应该是这样的
get todoList() {
const todoList = [];
return this.todos.iterate((value,id) =>{
let item = { id, title: value.title};
if (value.prioritized === true) {
todoList.unshift(item);
} else {
todoList.push(item);
}
}).then(() => {
console.log('Got todo list');
return todoList
}).catch((err) => {
console.log(`There was an error: ${err}`);
});
},
在 'then' 中,我在 Promise 中返回我真正想要的数组。第二种方法应该是这样的
displayTodos() {
store.todoList.then(arr=> arr.forEach((item) => {
console.log(item.title);
}))
}
我使用的结果是一个 Promise,所以我必须在“then”内工作才能看到数组
推荐阅读
- java - GraphQL Federation:是否有 Java Springboot 网关
- android - 应用程序中未调用 Lifecycle.Event.ON_DESTROY
- angular - 为什么在带有异步管道的 Angular 模板中未检测到 Subject.next () 发射?
- repository - Nexus Repository manager OSS 3 代理和保存
- python - 如何检查 tkinter 窗口是否已最小化?
- mysql - 如何在 MySQL 中使用 FULLTEXT 查询来返回与字符串匹配的所有结果?
- python - DOCKER_BUILDKIT - 在构建期间从 github 操作传递令牌秘密
- python - Python3 帮助,2 个同时运行的任务,一个需要来自另一个的数据
- azure-devops-migration-tools - 无法正确配置 TeamSettingsProcessor
- ios - 如何更改 AVAudioFormat 的 AVFormatIDKey?