uniapp如何将微信小程序API封装为Promise


 1 var SYNC_API_RE = /requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$/;
 2 
 3 var CALLBACK_API_RE = /^on/;
 4 // 微信同步api
 5 function isSyncApi(name) {
 6     return SYNC_API_RE.test(name);
 7 }
 8   
 9 function isCallbackApi(name) {
10     return CALLBACK_API_RE.test(name);
11 }
12 // 是否应该使用promise
13 function shouldPromise(name) {
14     if (isSyncApi(name)) {
15       return false;
16     }
17     if (isCallbackApi(name)) {
18       return false;
19     }
20     return true;
21   }
22 // 使用promise
23 function handlePromise(promise) {
24     return promise.then(function (data) {
25       return [null, data];
26     }).
27     catch(function (err) {return [err];});
28   }
29 // 异步处理的使用promise
30 function promisify(name, api) {
31     if (!shouldPromise(name)) {
32         return api;
33     }
34     return function promiseApi() {
35         var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
36         // 参数 --> 数组(可以简化吧)
37         for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
38             params[_key - 1] = arguments[_key];
39         }
40         // 如果以原始方式传入则调用原始方式
41         if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
42             return api.apply(void 0, [options].concat(params));
43         }
44         // 否则返回promise方式
45         return handlePromise(
46         new Promise(
47             function (resolve, reject) {
48                 // options 为url等等配置
49             api.apply(void 0, [Object.assign({}, options, {
50                 success: resolve,
51                 fail: reject })].concat(
52             params)
53         );
54         /* eslint-disable no-extend-native */
55         Promise.prototype.finally = function (callback) {
56             // Promise 构造器对象,它身上有Promise.resolve()
57             var promise = this.constructor;
58             // Promise 实例化对象
59             return this.then(
60             function (value) {return promise.resolve(callback()).then(function () {return value;});},
61             function (reason) {return promise.resolve(callback()).then(function () {
62                 throw reason;
63             });});
64 
65         };
66         }));
67     };
68 }

都附上标注了,纯属个人理解,自己改吧改吧就能用,本人技术比较渣,只能学别人的代码!自己标注的,有不对的地方可以留言!不懂得地方也可以问我


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM