前言
小程序一直到現在接口還是和剛開始一樣使用的回調函數的方式,如果想在小程序中不使用框架的情況下使用Promise+Async怎麼辦呢?
2019最新解決方案
1. 將接口Promise化
首先建一個文件wxPromise.js
const promisify = name => option => {
return new Promise((resolve, reject) =>
wx[name]({
...option,
success: resolve,
fail: reject,
})
)
}
const wxPro = new Proxy(wx, {
get(target, prop) {
return promisify(prop)
}
})
export default wxPro
2.使用regeneratorRuntime讓小程序兼容async函數
在github項目regenerator裏下載packages/regenerator-runtime/runtime.js。
如果是最新版本的話引入後會報一個錯誤:
Function is not a function....
需要手動修改源碼:
去掉源碼最後的try-catch語句,並將開頭的var runtime改成var regeneratorRuntime。
如果不想修改則可以直接下載0.13.1版本的源碼。
最後
在想使用的頁面裏引入:
import wxPro from './utils/wxPromise.js'
import regeneratorRuntime from './utils/runtime.js'
//app.js
App({
async onLaunch() {
// wxPro.login().then((res) => {
// console.log(res)
// })
const result = await wxPro.login()
console.log(result)
},
globalData: {
userInfo: null
}
})
這樣就可以了,唯一有點麻煩的是每個要用的頁面都要引入一次。