使用await但函数立即返回

问题描述 投票:0回答:1

我有一个正在尝试调用的函数,其签名如下

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

我知道这个函数返回一个承诺

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(...)
,代码执行也会继续,并且
export const getResponse
的调用者会收到
undefined
值。

有没有办法可以强制代码在回调有响应之前不返回?

reactjs react-native callback
1个回答
0
投票
public async submit(
  value: string,
  callbackFn: (response: string[]) => void
): Promise<string[]> {
  return new Promise<string[]>((resolve, reject) => {
    setTimeout(() => {
      try {
        const response = [value, "response"];
        callbackFn(response);
        resolve(response); 
      } catch (error) {
        reject(error); 
      }
    }, 1000);
  });
}

// Define the getResponse function
export const getResponse = async (
  service: Service,
  input: string
): Promise<string[]> => {
  try {
    const result = await service.submit(
      input,
      (response) => {
        console.log("Callback response:", response);
      }
    );

    return result;
  } catch (error) {
    console.log(error);
    throw error;
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.