我有以下对象文字,试图在存储对象(使用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方法中调用toEach()或对todoList进行任何其他类型的数组操作均不起作用。这是怎么回事?
答案 0 :(得分:0)
第一种方法应该是这样
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'内部工作才能看到数组