Skip to content

[vue] 如果将axios异步请求同步化处理? #328

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] 如果将axios异步请求同步化处理?

Activity

zyronon

zyronon commented on Jul 7, 2019

@zyronon

async ,await

HeMin0919

HeMin0919 commented on Jul 27, 2019

@HeMin0919
// 统一处理axios请求
    async getHistoryData (data) {
      try {
        let res = await axios.get('/api/survey/list/', {
          params: data
        })
        this.tableData = res.data.result
        this.totalData = res.data.count
      } catch (err) {
        console.log(err)
        alert('请求出错!')
      }
    }
  }
guoyiheng

guoyiheng commented on Jul 30, 2019

@guoyiheng

async ,await
Generator函数
回调里面写回调

hyj443

hyj443 commented on Oct 21, 2021

@hyj443
async getHistoryData (data) {
   try {
        let res = await axios.get('/api/survey/list/', {
          params: data
        })
        this.tableData = res.data.result
        this.totalData = res.data.count
      } catch (err) {
        console.log(err)
        alert('请求出错!')
      }
   }
}

同步的axios.get调用返回的是一个状态为pending的promise,等异步请求有了结果,这个promise的状态就会settled,要么成功要么失败了
最好对axios.get进行一层promise的封装,单独写在一个文件里,对它的返回结果调用then,在成功回调中solve,在失败回调中reject

异步有了结果后,res就能拿到成功的response,没有结果的时候this.tableData = res.data.result代码是阻塞不执行的

这种async await的写法,只是写法上同步化了

Cai-zhiji

Cai-zhiji commented on Jul 7, 2023

@Cai-zhiji

使用async/await结合Promise来实现一种类似同步的代码风格,使代码看起来更加同步化。

定义一个异步函数:

在合适的地方(如Vue组件的方法中)定义一个异步函数,用于执行异步操作。

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    // 处理响应数据
    console.log(response.data);
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

调用异步函数:

在需要执行异步请求的地方,调用定义的异步函数。

methods: {
  async getData() {
    await fetchData();
    // 在异步请求完成后继续执行其他逻辑
    console.log('Data fetching completed');
  },
}

通过使用async/await,你可以在异步请求的地方使用await关键字等待异步操作的完成,并根据结果进行后续处理。但请注意,这仅是一种语法糖,实际上仍然是异步执行的,不会阻塞JavaScript的执行。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@zyronon@guoyiheng@hyj443@HeMin0919

        Issue actions

          [vue] 如果将axios异步请求同步化处理? · Issue #328 · haizlin/fe-interview