-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
71 lines (65 loc) · 1.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Created by Bell on 16/10/19.
*/
const promise = module.exports = {};
promise.default = promise;
/**
* promise.app ==> getApp()
*/
Object.defineProperty(promise, 'app', {
get: function () {
return getApp();
}
});
/**
* 没有 success fail 回调
*/
var noPromiseMethods = {
stopRecord: true,
pauseVoice: true,
stopVoice: true,
pauseBackgroundAudio: true,
stopBackgroundAudio: true,
showNavigationBarLoading: true,
hideNavigationBarLoading: true,
createAnimation: true,
createContext: true,
hideKeyboard: true,
stopPullDownRefresh: true
};
function forEach(key) {
if (noPromiseMethods[key] || key.substr(0, 2) === 'on' || /\w+Sync$/.test(key)) { // 没有 success fail 回调,以 on 开头,或以 Sync 结尾的用原始的方法
promise[key] = function () {
if (__DEBUG__) {
var res = wx[key].apply(wx, arguments);
if (!res) {
res = {};
}
if (res && typeof res === 'object') {
res.then = function () {
console.warn('wx.' + key + ' is not a async function, you should not use await ');
};
}
return res;
}
return wx[key].apply(wx, arguments);
};
return;
}
// 转成 promise
promise[key] = function (obj) {
obj = obj || {};
return new Promise(function (resolve, reject) {
obj.success = resolve;
obj.fail = function (res) {
if (res && res.errMsg) {
reject(new Error(res.errMsg));
} else {
reject(res);
}
};
wx[key](obj);
});
};
}
Object.keys(wx).forEach(forEach);