在微信小程序中,methods 中的方法默认是同步的,但可以根据需要写成异步的。

在微信小程序中,methods 中的方法默认是同步的,但可以根据需要写成异步的。

默认同步执行

Page({
  data: {
    count: 0
  },
  
  methods: {
    // 默认同步方法
    increment() {
      this.setData({
        count: this.data.count + 1
      })
      console.log('同步执行完成')
    }
  }
})

如何写成异步:2 种

1,异步方法 - 使用 async/await
2,异步方法 - 使用 Promise

Page({
 data: {
   userInfo: null
 },
 
 methods: {
   // 异步方法 - 使用 async/await
   async fetchUserInfo() {
     try {
       const res = await wx.request({
         url: 'https://api.example.com/user',
         method: 'GET'
       })
       this.setData({
         userInfo: res.data
       })
     } catch (error) {
       console.error('请求失败:', error)
     }
   },
   
   // 异步方法 - 使用 Promise
   fetchData() {
     return new Promise((resolve, reject) => {
       wx.request({
         url: 'https://api.example.com/data',
         success: (res) => {
           this.setData({ data: res.data })
           resolve(res)
         },
         fail: reject
       })
     })
   }
 }
})

实际使用场景

// 在页面中调用
onLoad() {
  // 调用同步方法
  this.increment()
  
  // 调用异步方法
  this.fetchUserInfo()
  
  // 等待异步方法完成
  this.fetchData().then(() => {
    console.log('数据加载完成')
  })
}

总结

  • 默认同步:普通函数按顺序同步执行

  • 支持异步:可以使用 async/await、Promise 或回调函数实现异步操作

  • 常见异步场景:网络请求、文件操作、定时器等小程序 API 调用

小程序本身很多 API 都是异步的(如 wx.request、wx.login 等),所以在 methods 中处理这些 API 时通常需要异步编程。

end