-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
122 lines (102 loc) · 3.71 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// 不再维护,请使用 atinterceptor
function setConfigs(key, value) {
return {
...this,
configs: {
...this.configs,
[key]: value
}
};
}
function fetchDataMemoize(asyncOperateTag) {
asyncOperateTag = {
...asyncOperateTag
};
return (getAsyncTaskArray, tagKey, onAsyncOperateTagChange) => {
argsValidate(getAsyncTaskArray, tagKey, onAsyncOperateTagChange);
const configs = this.configs;
return new Promise((resolve, reject) => {
if (!asyncOperateTag[tagKey]) {
asyncOperateTag[tagKey] = 'init';
}
if (asyncOperateTag[tagKey] == 'loading') {
return reject({
[configs.errorTypeKey]: 'req:q2',
[configs.msgKey]: '重复提交',
});
}
asyncOperateTag[tagKey] = 'loading';
onAsyncOperateTagChange && onAsyncOperateTagChange(asyncOperateTag);
const asyncTaskArray = getAsyncTaskArray();
return Promise.all(asyncTaskArray).then((result) => {
const hasError = result.some((item) => {
if (configs.resS1ErrorCase(item)) {
reject({
...item,
[configs.errorTypeKey]: 'res:s1',
});
return true;
}
});
if (hasError) {
return;
}
asyncOperateTag[tagKey] = 'success';
onAsyncOperateTagChange && onAsyncOperateTagChange(asyncOperateTag);
return resolve(configs.successFilter(result));
}).catch((tmpError) => {
// 注意这里包含的错误类型可能比较多,真正的错误信息会打印
// 这里把错误统一归结为 res:s2
console.error(tmpError);
const error = {
...tmpError,
[configs.errorTypeKey]: 'res:s2',
[configs.msgKey]: '系统繁忙',
};
reject(error);
});
}).catch((tmpError) => {
console.error(tmpError);
const error = {
...tmpError,
};
if (!error[configs.errorTypeKey]) {
asyncOperateTag[tagKey] = 'error';
onAsyncOperateTagChange && onAsyncOperateTagChange(asyncOperateTag);
} else {
if (error[configs.errorTypeKey] == 'req:q2') {
// 重复提交,不修改 tag
}
// res s1 s2 error
if (error[configs.errorTypeKey].indexOf('res:s') != -1) {
asyncOperateTag[tagKey] = 'error';
onAsyncOperateTagChange && onAsyncOperateTagChange(asyncOperateTag);
}
configs.errorCb(error);
}
throw error;
});
};
}
function argsValidate(getAsyncTaskArray, tagKey, onAsyncOperateTagChange) {
if (!getAsyncTaskArray || typeof getAsyncTaskArray !== 'function') {
throw 'getAsyncTaskArray 参数错误';
}
if (!tagKey || typeof tagKey !== 'string') {
throw 'tagKey 参数错误';
}
if (onAsyncOperateTagChange && typeof onAsyncOperateTagChange !== 'function') {
throw 'onAsyncOperateTagChange 参数错误';
}
}
function factory(configs) {
return {
configs: {
...configs,
},
setConfigs,
fetchDataMemoize,
};
}
// export default factory; // 为了兼容 node 服务端,使用 CommonJS 规范
module.exports = factory;