在工程化项目中我们往往需要通过接口拿到初始化配置信息,拿到配置信息之后再去通过接口获取其他信息,但是为了用户体验,我们可能不会等待初始化信息完全获取之后再走后面的逻辑,配置接口信息什么时候回来是异步的,而其他有用到配置信息的接口可能先调用了,这种场景的处理我们经常遇到,这时候我们改如何完美处理呢?!
下面我写这样一套代码
import { getMyConfig } from "@/common/api";
import Config from "./Config";
export default class ConfigUtils {
private static config = null;
private static callbackResolves = [];
static async initConfig() {
const response = await getMyConfig();
this.config = response;
this.callbackResolves.forEach((resolve) => resolve(this.config));
return this.config;
}
static getConfig(): Promise<Config> {
return new Promise((resolve) => {
if (this.config) {
resolve(this.config);
} else {
this.callbackResolves.push(resolve);
}
})
}
}
import Config from '@/common/utils/Config';
import ConfigUtils from '@/common/utils/ConfigUtils';
import { getCountryCode } from '@/api';
import { countryDictCodeList } from '@/common/consts/countryDictCode';
import { filter } from 'lodash-es';
export default class CountryCodeUtils {
private static countryDigitCode;
private static countryCode;
private static defaultCountryCode = 'CN';
private static defaultCountryDigitCode = '156';
private static callbackResolves = {
countryCode: [],
countryDigitCode: [],
};
static async initCountryCode() {
const mapConfig: Config = await ConfigUtils.getConfig();
const { mapUrl }: Config = mapConfig;
const response = await getCountryCode(mapUrl);
if (response?.data?.countryDigitCode) {
const countryObj = filter(countryDictCodeList, [
'countryDictCode',
Number(response.data.countryDigitCode),
])[0];
this.countryCode = countryObj.countryCode;
this.countryDigitCode = countryObj.countryDictCode;
} else {
// 接口报错, 设置null标记避免get操作被阻塞
this.countryCode = null;
this.countryDigitCode = null;
}
this.callbackResolves.countryCode.forEach((resolve) => resolve());
this.callbackResolves.countryDigitCode.forEach((resolve) => resolve());
}
static getCountryCode(hasDefault = true): Promise<string> {
return new Promise((resolve) => {
if (this.countryCode !== undefined) {
resolve(
this.countryCode || hasDefault
? this.countryCode
: this.defaultCountryCode
);
} else {
this.callbackResolves.countryCode.push(() => {
resolve(
this.countryCode || hasDefault
? this.countryCode
: this.defaultCountryCode
);
});
}
});
}
static getCountryDigitCode(hasDefault = true): Promise<string> {
return new Promise((resolve) => {
if (this.countryDigitCode !== undefined) {
resolve(
this.countryDigitCode || hasDefault
? this.countryDigitCode
: this.defaultCountryDigitCode
);
} else {
this.callbackResolves.countryDigitCode.push(() => {
resolve(
this.countryDigitCode || hasDefault
? this.countryDigitCode
: this.defaultCountryDigitCode
);
});
}
});
}
}
使用
// 先初始化配置信息
ConfigUtils.initConfig();
// 获取配置信息
const config: Config = await ConfigUtils.getMyConfig();
const { codeUrl }: Config = config;
const response = await getMyCode(codeUrl);
可以做个打印测试,发现初始化信息还没返回,第二个接口就已经触发了,但是经过await 之后,是确保可以获取到接口返回数据之后继续往下执行滴。
点赞加关注,永远不迷路








网友评论