File tree Expand file tree Collapse file tree 5 files changed +90
-1
lines changed
Expand file tree Collapse file tree 5 files changed +90
-1
lines changed Original file line number Diff line number Diff line change 1+ # IDE
2+
3+ # repo
4+ node_modules
5+
6+ # test
7+ test
Original file line number Diff line number Diff line change 1+ 回顾
2+ ========
3+
4+ ## 参考阅读
5+
6+ * [ 让微信小程序支持 ES6 的 Promise 特性] ( https://haojen.github.io/2016/11/23/wechat-app-promise/ )
Original file line number Diff line number Diff line change 1+ 在小程序中使用 Promise
2+ ========
3+
4+ 小程序里由于要跟原生应用做交互,大部分 API 都是用异步回调实现的,所以自然而然的,我就想用更好的方式去操作。
5+
6+ 因为客户端的 WebView 中不包含原生 Promise,所以“微信 Web 开发工具”中也移除了对 Promise 的支持,需要我们自己处理。
7+
8+ 如同之前所说,Promise 不需要引入新的语言元素,自然兼容性上佳,所以我们只要引用成熟的 Promise 类库就好。这里我选择的是 [ Bluebird] ( http://bluebirdjs.com/ ) 。
9+
10+ ## 安装
11+
12+ ``` bash
13+ cd /path/to/my-xcx
14+ npm install bluebird --save-dev
15+ ```
16+
17+ 这样会把 Bluebird 安装在小程序目录的 ` node_modules ` 里。因为小程序并不支持从中加载,所以我们需要手工把 ` node_modules/bluebird/browser/bluebird.js ` 复制出来,放到小程序的 ` utils ` 目录内。
18+
19+ ## 使用
20+
21+ 使用时只需要 ` import Promise from './utils/bluebird'; ` ,就可以在开发环境中自由使用 ` new Promise() ` 了。这里拿 ` wx.login ` 作为例子:
22+
23+ ``` javascript
24+ import Promise from ' ./utils/bluebird' ;
25+
26+ return new Promise (resolve => {
27+ wx .login ({
28+ success (result ) {
29+ resolve (result);
30+ }
31+ });
32+ })
33+ .then (result => {
34+ console .log (result);
35+ });
36+ ```
37+
38+ ## 注意事项
39+
40+ 经过我的实际测试,在小程序里抛出错误并不会被 ` .catch() ` 捕获,而是直接进入全局错误处理。所以在小程序开发中,我们需要放弃前面说的,尽量抛出错误的做法,转用 ` reject() ` 。
41+
42+ ``` javascript
43+ // 不要这样做!
44+ new Promise ( resolve => {
45+ wx .checkSession ({
46+ success () {
47+ resolve ();
48+ },
49+ fail () {
50+ throw new Error (' Weixin session expired' );
51+ }
52+ });
53+ });
54+
55+ // 这样做是可以的
56+ new Promise ( (resolve , reject ) => {
57+ wx .checkSession ({
58+ success () {
59+ resolve ();
60+ },
61+ fail () {
62+ reject (' Weixin session expired' );
63+ }
64+ });
65+ });
66+ ```
67+
68+ ## Await/Async
69+
70+ “微信 Web 开发者工具”里面集成了 Babel 转译工具,可以将 ES6 编译成 ES5,不过 Await/Async 就不支持了。此时我们可以选择自行编译,或者只使用 Promise。
71+
72+ 自行编译时,请注意,小程序页面没有 ` <script> ` ,只能引用同名 ` .js ` ,所以要留神输出的文件名哟。这里建议把 JS 写在另一个文件夹,然后用 Babel 转译的时候再写过来。
73+
74+ ``` bash
75+ babel /path/to/my-xcx-src -d /path/to/my-xcx --source-map --watch
76+ ```
Original file line number Diff line number Diff line change 77 * [ Promise 进阶] ( 02-2-promise-advanced.md )
88 * [ Node.js 8 的新方法] ( 02-3-node-js.md )
99* [ Await/Async 方案] ( 03-await-async-.md )
10- * [ 总结 ] ( 10-overview .md )
10+ * [ 回顾 ] ( 10-review .md )
1111* [ Tips:小程序] ( 20-1-xiaochengxu.md )
1212* [ Tips:改进老代码] ( 20-2old.md )
You can’t perform that action at this time.
0 commit comments