JavaScript async/await使用疑问:then回调中await无法生效求助
Fixing the
await Issue in Your JavaScript Async Function Hey there, let's break down why your await isn't working and get your code sorted out!
The Core Problems
Two key missteps are causing your issue:
- You’re using
awaitin a non-async function: The callback inside your.then()is a regular function, not marked withasync. JavaScript throws an error if you try to useawaitanywhere that isn’t inside an async function. - You don’t need
awaitforArray.find():find()is a synchronous array method—it runs immediately and returns a result right away, no promise involved. Wrapping it inawaitdoesn’t do anything useful here, and would cause an error even if the callback was async.
The Cleanest Fix: Ditch .then() for Full async/await Syntax
The whole point of async/await is to replace messy .then() chains with linear, easy-to-read code. Here's how to rewrite your function properly:
const bookAppointment = async (data) => { try { // Wait for the User.findOne promise to resolve const userfound = await User.findOne({_id: data.user_id}); // Array.find is synchronous—no await needed! const found = userfound.dataArray.find(element => element.data === data.user_data); // Now you can run your conditional checks immediately with the found value if (found) { // Do something if the element exists console.log("Matching element found:", found); } else { // Handle the case where no match exists console.log("No matching element found"); } // Add any other logic you need here—it will run after the above steps } catch (error) { // Catch and handle any errors from User.findOne (like no user found) console.error("Error fetching user:", error); } };
If You Insist on Keeping .then() (Not Recommended)
If you need to keep the .then() structure for some reason, you have to mark the callback as async—but note that mixing two async patterns makes your code harder to follow:
const bookAppointment = async (data) => { return User.findOne({_id: data.user_id}) .then(async (userfound) => { // Mark the callback as async // Still no await needed for Array.find! const found = userfound.dataArray.find(element => element.data === data.user_data); // Run your conditional checks here }) .catch(error => { // Handle errors from the promise chain console.error(error); }); };
Quick Reminders for Future Async Code
- Only use
awaitwith promises: Async operations like database calls, fetch requests, or timers return promises—those are the only thingsawaitworks on. Sync methods (array functions, basic calculations) don’t need it. - Wrap async code in
try/catch: This replaces the.catch()in promise chains and lets you handle errors cleanly. awaitonly works insideasyncfunctions: Any function usingawaitmust be marked withasync, including callbacks if you absolutely have to use them.
内容的提问来源于stack exchange,提问作者Mubashar Rasheed
相关产品推荐
相关产品推荐

