从 then() returns Promise<void> 而不是 Promise<data> 返回数据

returning data from then() returns Promise<void> instead of Promise<data>

我正在从 API 中获取数据,如下所示:

export const getSymbolStats = async (symbol: string) => {
let requiredData: IRequiredSymbolStats;
let request: Promise<AxiosResponse> = axios.get(`${api.baseURL}${api.symbolStats}`, {params: {symbol}});

request.then((res: AxiosResponse<ISymbolStats>) => {
    const symbolStats: ISymbolStats = res.data;

    // Destructure symbol stats.
    const highPrice: string = symbolStats.highPrice;
    const lowPrice: string = symbolStats.lowPrice;
    const priceChangePercent: string = symbolStats.priceChangePercent;
    const volume: string = symbolStats.volume;
    const weightedAvgPrice: string = symbolStats.weightedAvgPrice;

    // return an object with the required data.

    requiredData = {
        symbol,
        highPrice,
        lowPrice,
        priceChangePercent,
        volume,
        weightedAvgPrice,
    };
    return requiredData;
})
}

并在此函数中检索数据:

export const getStats = async (msg: Message, match: RegExpExecArray | null): Promise<void> => {
  const id = msg.chat.id;
  const symbol: OrUndefined<string> = validateSymbol(id, match);
  if (!symbol) return;

  // make API call to get stats for symbol.
  let data = await getSymbolStats(symbol);

};

第二个函数中的 data 显示 void 而不是我在 then() 块中返回的 IRequiredSymbolStats 类型。这是为什么?

  1. 如果您将函数声明为 async,则无需使用 then.
  2. return 来自 then 的内容无处可去,因为您不存储也不会 return 来自 getSymbolStats

只需使用 await 并存储结果或在 request.then 之前添加 return

with await(更直接的代码,我更喜欢这种方式)。

const res: AxiosResponse<ISymbolStats> = await axios.get<ISymbolStats>(`${api.baseURL}${api.symbolStats}`, {params: {symbol}});

const symbolStats: ISymbolStats = res.data;

// Destructure symbol stats.
const highPrice: string = symbolStats.highPrice;
const lowPrice: string = symbolStats.lowPrice;
const priceChangePercent: string = symbolStats.priceChangePercent;
const volume: string = symbolStats.volume;
const weightedAvgPrice: string = symbolStats.weightedAvgPrice;

// return an object with the required data.

requiredData = {
  symbol,
  highPrice,
  lowPrice,
  priceChangePercent,
  volume,
  weightedAvgPrice,
};
return requiredData;

添加return:

let request: Promise<AxiosResponse> = axios.get(`${api.baseURL}${api.symbolStats}`, {params: {symbol}});

return request.then((res: AxiosResponse<ISymbolStats>) => {
    const symbolStats: ISymbolStats = res.data;

    // Destructure symbol stats.
    const highPrice: string = symbolStats.highPrice;
    const lowPrice: string = symbolStats.lowPrice;
    const priceChangePercent: string = symbolStats.priceChangePercent;
    const volume: string = symbolStats.volume;
    const weightedAvgPrice: string = symbolStats.weightedAvgPrice;

    // return an object with the required data.

    requiredData = {
        symbol,
        highPrice,
        lowPrice,
        priceChangePercent,
        volume,
        weightedAvgPrice,
    };
    return requiredData;
})