异步场景下数组总烹饪时间计算偶现Undefined值问题求助
Let's break down what's going wrong here step by step—your code has a mix of syntax errors, logical gaps, and missing async handling that's causing those inconsistent undefined returns and lack of proper time calculation.
1. 语法错误(Syntax Errors)
Looking at your cookDinner function, there are unclosed brackets and parentheses all over the place:
- The
cookCarbscallback function isn't closed (no});at the end) - The
arr.forEachcallback isn't closed - The entire
cookDinnerfunction is missing its closing}
JavaScript parsers can sometimes recover from partial syntax errors in unpredictable ways, which is why you might get random results instead of a consistent error. This is the first critical issue to fix.
2. 缺失异步逻辑处理(Missing Async Handling)
Assuming cookMeat and cookCarbs are asynchronous functions (since they accept callbacks), your current code doesn't wait for them to complete before moving on. Worse, you're calling both functions inside every forEach iteration—meaning you're trying to cook meat and carbs three times (once per meal in the array), which isn't your intended logic.
You also never track the actual cooking time values, and never invoke the cb callback passed to cookDinner, so there's no way to pass the final total time back to the caller.
3. 未实现时间计算逻辑(No Time Calculation Logic)
Your cookingTime function only logs the input instead of calculating a total. You need to define how each meal contributes to the total cooking time (e.g., meat takes 30 mins, carbs 20, veg 15—summing to 65) and actually compute that sum.
修复后的示例代码
Here's a fixed version that properly handles async operations, calculates total time, and avoids syntax errors:
// Define cooking times for each meal type const mealTimes = { meat: 30, carbs: 20, veg: 15 }; // Async cooking functions that simulate delay and return time taken function cookMeat(callback) { setTimeout(() => { callback(null, mealTimes.meat); }, 1000); } function cookCarbs(callback) { setTimeout(() => { callback(null, mealTimes.carbs); }, 1000); } function cookVeg(callback) { setTimeout(() => { callback(null, mealTimes.veg); }, 1000); } // Calculate total cooking time function cookingTime(total) { return total; } function cookDinner(arr, cb) { let totalTime = 0; let mealsProcessed = 0; arr.forEach(meal => { // Call the appropriate cooking function for each meal let cookFunction; switch(meal) { case 'meat': cookFunction = cookMeat; break; case 'carbs': cookFunction = cookCarbs; break; case 'veg': cookFunction = cookVeg; break; default: cookFunction = (cb) => cb(null, 0); } cookFunction((err, time) => { if (!err) { totalTime += time; } mealsProcessed++; // When all meals are processed, call the callback with total time if (mealsProcessed === arr.length) { cb(null, cookingTime(totalTime)); } }); }); } // Usage const arr = ['meat', 'carbs', 'veg']; cookDinner(arr, (err, total) => { if (!err) { console.log(total); // Will consistently log 65 } });
Key Fixes:
- Fixed all syntax errors to ensure the code parses correctly every time
- Added proper async tracking: we count processed meals and only call the callback once all are done
- Mapped each meal type to its corresponding cooking function and time value
- Implemented actual time calculation in
cookingTime(you can expand this logic if needed) - Ensured we only cook each meal once, not multiple times per array item
内容的提问来源于stack exchange,提问作者squeekyDave

