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

使用await但函数立即返回,如何等待回调响应?

问题:如何让异步回调完成后再返回结果?

我调用的函数签名如下:

public async submit(
  value: string,
  callbackFn: (response: string[]) => never | void
): Promise<void>

该函数返回Promise<void>,但参数中包含一个可接收响应的回调函数。我通过以下方式调用它:

export const getResponse = async (
  service: Service,
  input: string
): Promise<string[]> => {
  try {
    const result = await service.submit(
      input,
      (response) => {
        return response;
      }
    );

    return Promise.resolve(result as string[]);
  } catch (error) {
    console.log(error);
    throw error;
  }
};

调试时发现,即使使用了await service.submit(...),代码仍会继续执行,getResponse的调用者会收到undefined值。请问有没有办法让代码在回调返回响应前不返回?


解决方案

问题出在submit返回的Promise<void>并不会等待传入的回调函数执行完成,所以await之后代码会直接继续往下走,此时result就是undefined,返回给调用者自然也是undefined。

要实现等待回调完成后再返回,你可以把回调逻辑包裹在一个Promise中,通过resolve传递回调收到的响应:

export const getResponse = async (
  service: Service,
  input: string
): Promise<string[]> => {
  try {
    // 用Promise包裹submit调用,等待回调触发后resolve结果
    const result = await new Promise<string[]>((resolve) => {
      service.submit(
        input,
        (response) => {
          resolve(response);
        }
      );
    });

    return result;
  } catch (error) {
    console.log(error);
    throw error;
  }
};

这样修改后,getResponse会等待submit的回调函数触发并调用resolve(response)后,才会把结果返回给调用者,确保不会提前返回undefined。

内容的提问来源于stack exchange,提问作者user3587624

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:58:12