Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
haizhilin2013 opened this issue Jun 20, 2019 · 5 comments
Open

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

haizhilin2013 opened this issue Jun 20, 2019 · 5 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@zyronon
Copy link

zyronon commented Jul 7, 2019

async ,await

@HeMin0919
Copy link

// 统一处理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
Copy link

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

@hyj443
Copy link

hyj443 commented Oct 21, 2021

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
Copy link

使用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
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

6 participants