js怎么修改以下代码以顺序执行?

下面代码怎么可以叫上面的执行完成再执行下面的export { service }这句?

import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

import qs from 'qs'

import { config} from './config'


import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from "@/store/modules/app";
import { ElMessage } from "element-plus";



const { result_code, base_url } = config


export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH]


const { wsCache } = useCache()

const appStore = useAppStore()
//axios.defaults.baseURL='ssss'

let service:AxiosInstance|null=null;

axios.get('config.json').then(res=>{
  setTimeout(async ()=>{

    console.log('加载config.json')
    // 创建axios实例
    service=await axios.create({
      baseURL: res.data.baseUrl, // api 的 base_url
      timeout: config.request_timeout // 请求超时时间
    })

// request拦截器
    service.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        if (
          config.method === 'post' &&
          (config.headers as AxiosRequestHeaders)['Content-Type'] ==='application/x-www-form-urlencoded') {
          config.data = qs.stringify(config.data)
        }
        const token=wsCache.get(appStore.getUserInfo)?.Token;
        if(token){
          (config.headers as AxiosRequestHeaders)['Authorization'] = token
        }

        // ;(config.headers as AxiosRequestHeaders)['Token'] = 'test test'
        // get参数编码
        if (config.method === 'get' && config.params) {
          let url = config.url as string
          url += '?'
          const keys = Object.keys(config.params)
          for (const key of keys) {
            if (config.params[key] !== void 0 && config.params[key] !== null) {
              url += `${key}=${encodeURIComponent(config.params[key])}&`
            }
          }
          url = url.substring(0, url.length - 1)
          config.params = {}
          config.url = url
        }
        return config
      },
      (error: AxiosError) => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
      }
    )

// response 拦截器
    service.interceptors.response.use(
      (response: AxiosResponse<any>) => {
        if (response.config.responseType === 'blob') {
          // 如果是文件流,直接过
          return response
        } else if (response.data.code === result_code) {
          return response.data
        } else {
          //ElMessage.error(response.data.msg)
          return response.data
        }
      },
      (error: AxiosError) => {
        console.log('err' + error) // for debug
        //ElMessage.error(error.message)
        return Promise.reject(error)
      }
    )
  },1000)
}).catch(e=>{
  ElMessage.error('接口配置文件可以不存在'+e)
})


export { service }
阅读 1.4k
1 个回答

把外层拿掉,直接在interceptors.request.use 获取异步配置

axiosInstance.interceptors.request.use( async config => { config.baseURL=await getBaseUrl(); return config; }, error => Promise.reject(error) );
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏