You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从localforage获取数据?Promise解析及外部使用问题

Hey there! I see exactly what's tripping you up here—async code can be tricky when you're first working with Promises. Let's fix this step by step.

First, let's break down the two main issues in your code:

  1. Async execution order: localforage.getItem() is asynchronous, which means it runs in the background while the rest of your code keeps going. Your console.log(this.items) runs immediately, before the Promise resolves and the then callback updates this.items—so you're logging the empty initial array every time.
  2. this context mismatch: Inside the traditional function(data) callback, this doesn't refer to your outer object anymore. That means this.items = data isn't actually updating the this.items you think it is—it's setting a property on a different context entirely.

Fix 1: Use arrow functions to preserve this + handle async correctly

Arrow functions inherit the this context from their surrounding scope, so they'll fix the context issue. Plus, you need to move any code that depends on this.items inside the then callback (or after it in a chain), since that's the only place you know the data is ready:

this.items = [];
localforage.length().then((length) => { // Also, length() returns a Promise—don't compare it directly to 0!
  if (length !== 0) {
    localforage.getItem('items').then((data) => {
      this.items = data;
      console.log(this.items); // Now this logs the correct data!
      // Put any code that needs to use this.items here, like rendering your cart:
      // this.renderShoppingCart();
    });
  }
});

Fix 2: Use async/await for cleaner async code

If you can wrap this logic in an async function, await makes asynchronous code read like synchronous code, which is much easier to follow:

async loadShoppingCart() {
  this.items = [];
  const itemCount = await localforage.length();
  if (itemCount !== 0) {
    this.items = await localforage.getItem('items');
    console.log(this.items); // Data is ready here!
    this.renderShoppingCart(); // Run any dependent logic now
  }
}

// Call the async function to load your cart
this.loadShoppingCart();

Important note about localforage.length()

I noticed you tried checking localforage.length() != 0 directly—remember, almost all localforage methods return Promises, so you can't compare the Promise object itself to 0. You need to await it or use .then() to get the actual length value first, like in both solutions above.

内容的提问来源于stack exchange,提问作者Mary Maher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:27:02