axios关于同步执行ajax请求方法

axios关于同步执行ajax请求方法

调用函数要申明前缀async
内部函数调用要用await

// 上传图片 OK
    async UploadFile(file, fileList) {
      var that = this;
      //
      var api_dateitme = await ajax.ajax_tb(
        config.api_zt + "/api/sys/datetime",
        "get",
        {},
        null
      );
      // ajax.ShowJsonEq(api_dateitme.data.data)
      var t_datetime = api_dateitme.data.data;
      //同步获取日期后再使用t_datetime变量
      //....
   }   
// 同步
export async function ajax_tb_test(url, type, params, p_headers) {
  var result = await ajax_tb(url, type, params, p_headers)
  return result.data
}
// 定义ajax的promise函数
export function ajax_tb(url, type, params, p_headers) {
  return new Promise((resolve, reject) => {
    if (!p_headers) {
      // p_headers={ "Content-Type": "application/json" };
      p_headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
    }
    var tUrl = url
    if (type === 'post' || type === 'POST') {
      axios.post(tUrl, qs.stringify(params),{ headers: p_headers }).then(r => {
        resolve(r)
      }).catch(r => {
        gotoLoginPage(r)
      })
    }
    if (type === 'get' || type === 'GET') {
      axios.get(tUrl, {
        params: params
      }).then(r => {
        resolve(r)
      }).catch(r => {
        gotoLoginPage(r)
      })
    }
    if (type === 'put' || type === 'PUT') {
      axios.put(tUrl, params).then(r => {
        resolve(r)
      }).catch(r => {
        gotoLoginPage(r)
      })
    }
    if (type === 'delete' || type === 'DELETE') {
      axios.delete(tUrl, {
        params: params
      }).then(r => {
        resolve(r)
      }).catch(r => {
        gotoLoginPage(r)
      })
    }
    if (type === 'patch' || type === 'PATCH') {
      axios.patch(tUrl, params).then(r => {
        resolve(r)
      }).catch(r => {
        gotoLoginPage(r)
      })
    }
  })
}
// --
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页