H5W3
当前位置:H5W3 > 其他技术问题 > 正文

async 函数的使用

下面的函数 用 async函数 该如何写,请指教

  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
//fetchList
export function fetchList(query) {
  return request({
    url: '/article/list',
    method: 'get',
    params: query
  })
}
//request
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['X-Token'] = getToken()
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => response,
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service

回答:

async getList() {
      this.listLoading = true
        let response = await fetchList(this.listQuery)
        this.list = response.data.items
        this.total = response.data.total
        
        setTimeout(() => {
             this.listLoading = false
        }, 1.5 * 1000)
    },

回答:

var self = this;
(async function(){
    const response = await fetchList(self.listQuery);
    self.list = response.data.items
    self.total = response.data.total
    setTimeout(() => {
        self.listLoading = false
    }, 1.5 * 1000)
})()

根据补充的代码改成这样⬇️

    async getList() {
        const response = await fetchList(this.listQuery);
        this.list = response.data.items
        this.total = response.data.total
        setTimeout(() => {
            this.listLoading = false
        }, 1.5 * 1000)
    }

本文地址:H5W3 » async 函数的使用

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址