小程序API基本都是回调,为了防止回调地狱,原生小程序已支持 async/await。
async/await 是ES7的语法,用更加清晰的语义解决js异步代码。关于 async/await 学习可以去阮一峰老师的博客。
阮老师博客不知道啥时候添加反广告屏蔽脚本。打开chrome开发者工具,按照如下打开复选框,可以进行无耻的白嫖了。
Developer tools -> "Sources" tab -> Event Listener Breakpoints -> Load
小程序是不支持 async-await 语法的,可以使用 Facebook 开源库 regenerator。
如果版本引用不当错误信息,之所以出现 async 的错误,是因为regenerator-runtime版本升级导致在小程序环境出问题(动态 Function)锁定到0.12.1版本可以解决上述 async 问题
VM4677:1 thirdScriptError
sdk uncaught third Error
Function(...) is not a function
TypeError: Function(...) is not a function
Page is not constructed because it is not found.
- 下载 regenerator-runtime@0.12.1 注意版本号,开始我用的最新版一度怀疑人品有问题。
- 将下载到的目录 packages/regenerator-runtime 下的 runtime.js 文件放入 小程序 utils 目录下。
- 在需要使用 async/await 的js文件头部引入这个库文件。
- 别忘了勾选微信开发者工具的项目设置中 ES6 转 ES5
eg.
// index.js
import http from '../../../api/http'
import regeneratorRuntime from '../../../utils/runtime'
let _that
Component({
options: {
addGlobalClass: true,
},
data: {
list: []
},
lifetimes: {
_that = this
attached() {
_that.getBlogList()
}
},
methods: {
getBlogList: async () => {
await http('demo/list', {
hideLoading: true,
data: {
'a': 'abc'
}
})
.then(res => {
console.log(res)
})
}
}
})
上述 demo 中我用用到了箭头函数。如果想在小程序中使用箭头函数,可以定义一个全局变量 _that,并在 onLoad 或组件的 attached() 中把 this 做下赋值。否则会造成 this.setData 报错
只有一条评论 (QwQ)
感谢作者~用最新版 regenerator-runtime 真的让我怀疑人生。。Taro 的文档里说明了这个问题:https://nervjs.github.io/taro/docs/migrate-to-2.html#%E4%BD%BF%E7%94%A8-async-await-%E6%97%B6%E5%87%BA%E7%8E%B0%E6%8A%A5%E9%94%99-function-is-not-a-function