import { get } from './request' export class OneRequest { request: () => Promise; loading: boolean; done: boolean; res: any; callbacks: Array<{ resolve: (data: any) => void, reject: (err: any) => void }> = []; constructor(request: () => Promise) { this.request = request } async fetch() { this.loading = true try { this.res = await this.request() // 通知 res 请求完毕 this.syncRes(this.res, 'resolve') this.done = true } catch(err) { this.syncRes(err, 'reject') } this.loading = false return this.res } syncRes(data: any, type: 'resolve' | 'reject') { this.callbacks.forEach((callback) => { callback[type](data) }) } async oneFetch() { if (this.done) { return this.res } if (this.loading) { return new Promise((resolve, reject) => { this.callbacks.push({ resolve, reject }) }) } return await this.fetch() } } export const onBlogInfoRequest = new OneRequest( () => { return get('//www.lofter.com/loginCheck.do') } ) class templateActivityRequest { public oneInstance: { [key: string]: OneRequest } = {} getOneInstance(activityId: string) { if (this.oneInstance[activityId]) { return this.oneInstance[activityId] } let instance = new OneRequest( () => { return get(`//www.lofter.com/spread/common/getInfo.json?name=${activityId}`) } ) this.oneInstance[activityId] = instance return instance } } const templateActivityRequestIns = new templateActivityRequest() export const oneTemplateActivityRequest = (activityId: string) => { return templateActivityRequestIns.getOneInstance(activityId) }