首页 > 解决方案 > 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 执行任何其他类型的数组操作不起作用。这里发生了什么?

标签: javascriptecmascript-6localforage

解决方案


第一种方法应该是这样的

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”内工作才能看到数组


推荐阅读