You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将回调传入异步函数并二次包装是否合理?异步函数返回值作用域问题

Answers to Your Async/Callback Questions

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:

  1. You never actually call the debounced function you created (debounce is just the function reference, not an execution)
  2. There's no way to bridge the inner fetch's result to the outer test function'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 use resolve() to send the final json value up to the outer test function's return value.
  • We call the debounced function: Without debouncedFetch(), the fetch will never run at all.
  • Added error handling: Using try/catch (and checking response.ok) ensures errors from the fetch get passed to the outer .catch() if you add one in app.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:21:12