store值为undefined如何解决?是否应使用Async/await或Promise?
Hey there! Let's break down why you're seeing undefined for both the return value and store, then walk through solutions step by step.
The Core Problem: Asynchronous Code Behavior
Your db.read function is asynchronous—it starts the database read operation and immediately returns (which defaults to undefined), while the callback function you passed only runs after the read finishes. That means:
- The
return sendinside your callback doesn't get assigned tostore—it's returning to the callback's internal scope, not thedb.readcall itself. - When you log
storeright after callingdb.read, the read operation hasn't even completed yet, so there's no data to assign tostore.
Solution 1: Adjust Logic to Use the Callback Directly
If you want to stick with callbacks, don't try to assign the async result to a synchronous variable. Instead, move all code that needs the send value inside the callback:
db.read(collectionName, (status, data) => { if (status) { names.listOfData = data; const send = names; console.log("send---->", send); // Do everything you need to do with send HERE processSendData(send); } else { processSendData(null); } }); // Helper function to handle your data function processSendData(send) { console.log("Processing data:", send); // Add your logic that relied on `store` here }
Solution 2: Wrap db.read in a Promise (with Async/Await)
This is the cleaner, more modern approach for handling async code. First, wrap your callback-based db.read into a Promise:
function readCollection(collectionName) { return new Promise((resolve, reject) => { db.read(collectionName, (status, data) => { if (status) { // Make a copy of names instead of modifying the original (avoids side effects) const updatedNames = {...names}; updatedNames.listOfData = data; resolve(updatedNames); } else { reject(new Error("Failed to read from database")); } }); }); }
Then use async/await to get the result like it's synchronous:
async function getStoreData() { try { const store = await readCollection(collectionName); console.log("store-->", store); // Use store for your logic here } catch (error) { console.error("Error reading data:", error); // Handle failure case } } // Call the async function getStoreData();
Solution 3: Use Promise Chaining (No Async/Await)
If you can't use async/await (e.g., older environment), you can use Promise .then() and .catch() instead:
readCollection(collectionName) .then(store => { console.log("store-->", store); // Handle your data here }) .catch(error => { console.error("Read failed:", error); });
Quick Notes
- Never try to assign an async result to a synchronous variable—async results are only available after the operation completes, which happens later in the event loop.
- Avoid modifying the original
namesobject directly (like you did withnames.listOfData = data)—making a copy prevents unexpected side effects in other parts of your code.
内容的提问来源于stack exchange,提问作者Bcoder

