- 直接使用 async , await 会报错 regeneratorRuntime is not defined
- 下载第三方npm包 regenerator-runtime 下载地址
- 下载文件中的regenerator-runtime文件夹拿出来,放到小程序代码中去,一般是放在utils文件夹
- 查看下面示例 async应用
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)
})
}
})
- 控制台输出结果如图, async 函数返回的是一个 Promise 对象 , async 函数(包含函数语句、函数表达式、Lambda 表达式)会返回一个 Promise 对象,如果在函数中 return 一个直接量,async 会把这个直接量通过Promise.resolve() 封装成 Promise 对象。async 函数 在没有 await 的情况下执行async函数,它会立即执行,并且返回一个 promise 对象,并且绝不会阻塞后面的语句
- await 作用 表达式会暂停当前 async function 的执行,等待 Promise 处理完成若 Promise 正常处理,其处理结果作为 await 表达式的值,继续执行 async function 。若 Promise 处理异常 (rejected) , await 表达式会把 Promise 的异常原因抛出。另外,如果 await 操作符号的表达式的值不是一个 Promise ,那么该值将被转换为一个正常处理的 Promise 。
- async / await 的优势在于处理then链 ,查看下面示例
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')
})
},
})
- 输出结果异步变同步如图结果:先执行的one,等one完全执行结束 然后是two,最后是three
![微信小程序使用 async , await 微信小程序使用 async , await](https://image.shishitao.com:8440/aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzM1Ny8xMGI1NTRkYmY1YTlkYjE2NzJhOTQ2OTU4MzcwYzM5ZC5wbmc%3D.png?w=700&webp=1)
![微信小程序使用 async , await 微信小程序使用 async , await](https://image.shishitao.com:8440/aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzkzMi8yZDhhMTYwODAxOGVhYWFiMzFhNmY3MTRiM2NlNTA2Yy5wbmc%3D.png?w=700&webp=1)
本文内容借鉴er_ba的博客,推荐一下,大家相互学习