将回调传入异步函数并二次包装是否合理?异步函数返回值作用域问题
Hey there! Let's tackle your questions one by one, starting with whether your callback approach is valid, then fixing the issue of passing the fetch result outside the function.
Is passing callbacks into async functions (and wrapping them) a normal pattern?
Absolutely! This is a totally common pattern—especially when you need to control execution timing (like with debouncing/throttling, which you're doing here) or hook into specific stages of an async workflow. That said, modern JavaScript's Promise and async/await syntax can often make this code more readable and avoid "callback hell" compared to nested callback chains, but the core idea of wrapping or passing callbacks is totally valid.
How to pass the fetch json result outside the test function?
Your current code has two key issues preventing the result from escaping the inner scope:
- You never actually call the debounced function you created (
debounceis just the function reference, not an execution) - There's no way to bridge the inner fetch's result to the outer
testfunction's return value
Here's a fixed version of your asyncTest.js that resolves both problems, using a Promise to "carry" the result out of the debounced scope:
import _ from 'lodash'; // Make sure lodash is imported const test = async () => { // Wait for your initial async operation let data = await otherPromise(); // Wrap the debounced logic in a Promise so we can resolve the final result return new Promise((resolve, reject) => { // Create a debounced fetch function const debouncedFetch = _.debounce(async () => { try { // Run the fetch and parse the response const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); if (!response.ok) throw new Error(`Request failed: ${response.status}`); const json = await response.json(); // Pass the result to the outer Promise's resolve resolve(json); } catch (error) { // Handle errors and pass them to the outer Promise's reject reject(error); } }, 2000); // Don't forget to call the debounced function! debouncedFetch(); }); }; export default test;
Key changes explained:
- We wrap the debounced logic in a
Promise: This lets us useresolve()to send the finaljsonvalue up to the outertestfunction's return value. - We call the debounced function: Without
debouncedFetch(), the fetch will never run at all. - Added error handling: Using
try/catch(and checkingresponse.ok) ensures errors from the fetch get passed to the outer.catch()if you add one inapp.js.
Now your app.js code will work as expected—you'll get the fetch result in the .then() callback:
import test from "./asyncTest"; test() .then((result) => { console.log("Got the result:", result); // This will log the post data after 2 seconds }) .catch((error) => { console.error("Something went wrong:", error); });
内容的提问来源于stack exchange,提问作者JasonHsieh

