首页 > 解决方案 >

问题描述

标签: typescriptpromiseasync-awaites6-promise

解决方案


  1. 如果您将函数声明为async不需要使用 then.
  2. 你返回的东西then无处可去,因为你不存储也不返回它getSymbolStats

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

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;
})

推荐阅读