【发布时间】:2018-09-20 18:28:23
【问题描述】:
我有以下对象文字,我试图在存储对象(使用 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 执行任何其他类型的数组操作不起作用。这是怎么回事?
【问题讨论】:
-
因为
localForage的操作是异步的。这意味着您的数据在您返回之前尚未实际读取。将整个事情包装在一个 Promise 中并在你有got todo list!的地方解决它,然后使用store.todoList.then(array => renderview...)进行迭代
标签: javascript ecmascript-6 localforage