【问题标题】:Javascript, localForage, passing array between object literals with getterJavascript,localForage,使用getter在对象文字之间传递数组
【发布时间】: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


【解决方案1】:

第一种方法应该是这样的

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

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 2023-03-20
    • 2016-07-22
    • 2013-03-15
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多