如何从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:
- Async execution order:
localforage.getItem()is asynchronous, which means it runs in the background while the rest of your code keeps going. Yourconsole.log(this.items)runs immediately, before the Promise resolves and thethencallback updatesthis.items—so you're logging the empty initial array every time. thiscontext mismatch: Inside the traditionalfunction(data)callback,thisdoesn't refer to your outer object anymore. That meansthis.items = dataisn't actually updating thethis.itemsyou 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

