【问题标题】:Make sure Axios/Fetch call runs for at least X Seconds in Javascript确保 Axios/Fetch 调用在 Javascript 中运行至少 X 秒
【发布时间】:2021-06-04 03:41:09
【问题描述】:

奇怪的问题。如果我想确保我的查询至少运行 X 秒(例如 1 秒),你会如何解决这个问题?我有看起来像这样的 React Query,但实际上只需要 axios 调用就可以对其进行某种时间跟踪。

import axios from 'axios';
import { useQuery } from 'react-query';
import { themeKeys } from './themeKeys';
import { webApiBaseUrl, config } from "../apiConstants";

export const fetchTheme = (themeId) =>
    axios.get(`${webApiBaseUrl}/themes/${themeId}`, config)
        .then((res) => res.data);

export default function useTheme(themeId) {
    return useQuery(
        themeKeys.theme(themeId), 
        () => fetchTheme(themeId),
        {
            failureCount: 3,
            retryOnMount: false,
            refetchOnMount: false,
            refetchOnWindowFocus: false,
            refetchOnReconnect: false,
            cacheTime: Infinity,
            staleTime: Infinity
        }
    );
}

我有这样的事情增加了延迟,但不知道如何跟踪 axios 调用运行了多长时间以从 wait 中扣除

export const fetchTheme = async (themeId) => {
    return axios.get(`${webApiBaseUrl}/themes/${themeId}`, config)
        .then((res) => res.data)
        .then( await wait(750));
};

function wait(ms) {
    return new Promise( (resolve) => {
        setTimeout(resolve, ms);
    });
}

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

将你的两个承诺都放在Promise.all 中。这样,如果 fetch 先完成 Promise.all 将等待 wait 完成。

await Promise.all([fetchTheme(themeId), wait(750)])

【讨论】:

  • 我喜欢这个,但需要返回来自fetchTheme 的响应才能使其正常工作。承诺都返回什么?
  • const [result, _] = await Promise.all([fetch(), wait()]) 它返回一个解析结果数组
猜你喜欢
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
相关资源
最近更新 更多