微信小程序使用 async , await

时间:2024-03-22 17:04:03
  1. 直接使用 async , await 会报错 regeneratorRuntime is not defined
  2. 下载第三方npm包 regenerator-runtime 下载地址
  3. 下载文件中的regenerator-runtime文件夹拿出来,放到小程序代码中去,一般是放在utils文件夹
  4. 查看下面示例 async应用
//index.js
const regeneratorRuntime =require('../../utils/regenerator-runtime/runtime.js') 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async MyAsync(){
    return 'this is async function'
  },
  onLoad: function (options) {
    this.MyAsync().then((res)=>{
      console.log('1111'+res)
    })
  }
})
  1. 控制台输出结果如图, async 函数返回的是一个 Promise 对象 , async 函数(包含函数语句、函数表达式、Lambda 表达式)会返回一个 Promise 对象,如果在函数中 return 一个直接量,async 会把这个直接量通过Promise.resolve() 封装成 Promise 对象。async 函数 在没有 await 的情况下执行async函数,它会立即执行,并且返回一个 promise 对象,并且绝不会阻塞后面的语句微信小程序使用 async , await
  2. await 作用 表达式会暂停当前 async function 的执行,等待 Promise 处理完成若 Promise 正常处理,其处理结果作为 await 表达式的值,继续执行 async function 。若 Promise 处理异常 (rejected) , await 表达式会把 Promise 的异常原因抛出。另外,如果 await 操作符号的表达式的值不是一个 Promise ,那么该值将被转换为一个正常处理的 Promise 。
  3. async / await 的优势在于处理then链 ,查看下面示例
	//index.js
	const regeneratorRuntime =require('../../utils/regenerator-runtime/runtime.js') 
	Page({
	  /**
	   * 页面的初始数据
	   */
	  data: {
	    
	  },
	  /**
	   * 生命周期函数--监听页面加载
	   */
	  getOneMes() {
	    console.log('getOneMes one')
	    return new Promise((resolve, reject) => {
	      wx.request({
	        url: 'http://suggest.taobao.com/sug?code=utf-8&q=衣服&callback=cb',
	        method: 'GET',
	        dataType: 'json',
	        success: function (res) {
	          console.log('one:')
	          resolve(res)
	        },
	      })
	    })
	  },
	  getTwoMes() {
	    console.log('getOneMes two')
	    return new Promise((resolve, reject) => {
	      wx.request({
	        url: 'http://suggest.taobao.com/sug?code=utf-8&q=帽子&callback=cb',
	        method: 'GET',
	        dataType: 'json',
	        success: function (res) {
	          console.log('two:')
	          resolve(res)
	        },
	      })
	    })
	  },
	  getThreeMes() {
	    console.log('getOneMes three')
	    return new Promise((resolve, reject) => {
	      wx.request({
	        url: 'http://suggest.taobao.com/sug?code=utf-8&q=裤子&callback=cb',
	        method: 'GET',
	        dataType: 'json',
	        success: function (res) {
	          console.log('three:')
	          resolve(res)
	        },
	      })
	    })
	  },
	  async MyAsync(){
	    let one =await this.getOneMes()
	    console.log(one)
	    let two = await this.getTwoMes()
	    console.log(two)
	    let three = await this.getThreeMes()
	    console.log(three)
	  },
	  onLoad: function (options) {
	    this.MyAsync().then(()=>{
	      console.log('MyAsync')
	    })
	  },
	})	
  1. 输出结果异步变同步如图结果:先执行的one,等one完全执行结束 然后是two,最后是three微信小程序使用 async , await
    微信小程序使用 async , await
    本文内容借鉴er_ba的博客,推荐一下,大家相互学习