0%

封装一个autoTry函数,指定错误情况下重复执行次数,最终返回结果

一、封装 autoTry 函数

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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script>

function foo(params) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
JSON.parse('{{');
return resolve(params);
} catch (e) {
return reject(e);
}
}, 1000);
})
}

// ========doing======
function autoTry(fn, times) {
const retry = (params) => new Promise((resolve, reject) => {
fn(params).then(
(response) => { resolve(response) }
).catch(e => {
console.log('retrying: ' + new Date(), e)
if (times > 1) {
times -= 1
retry()
} else { reject(e) }
})
})

return retry
}

// ========test======
func = autoTry(foo, 3);
func({ a: 1, b: 2 }).then((res) => {
console.log(`结果:${JSON.stringify(res)}`);
}, (error) => {
console.log(error)
});

</script>
</body>

</html>

二、一个 n 个大小写字母组成的字符串按 ascii 码从小到大排序 查找字符串中第 k 个最小 ascii 码的字母输出该字母所在字符串位置索引

1
2
3
4
5
6
function lookup(str,key){
if(typeof str !='string'||key<1)return -1;
let value = str.split("").sort()[key-1];
return str.indexOf(value);
}
console.log(lookup('asasdskdjdfgnsdkfnmsASDdf',5)+1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let getIndexChar = (str,index)=>{
let sortChar = []
for(let i=0;i<str.length;i++) {
sortChar.push(str.charCodeAt(i))
}
sortChar = sortChar.sort((a,b)=>{
return a-b
})

let indexCode = -1
for(let i=0;i<str.length;i++) {
if(str[i].charCodeAt(0)==sortChar[index]) {
indexCode = i
}
}

return indexCode
}
getIndexChar('asdEQW',1) //4

三、ts 工具函数

1、实现一个 ts 的工具函数 GetOnlyFnProps ,提取泛型类型 T 中字段类型是函数的工具函数,其中 T 属于一个对象。

1
2
3
4
5
6
7
type GetOnlyFnKeys<T extends object> = {
[Key in keyof T]: T[K] extends Function ? K : never
}

type GetOnlyFnProps<T extends object> = {
[K in GetOnlyFnKeys<T>]: T[K]
}

实现一个 ts 的工具函数 UnGenericPromise ,提取 Promise 中的泛型类型

1
type UnGenericPromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never

四、分页加载

h5_demo

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
import React, { Component } from 'react';
import {PREFIX_URL ,request ,TITLE} from '../../common';
import DetailedList from "../../components/movie/DetailedListComponent";
import Loading from '../../components/common/LoadingComponent';

const PS = 5;
class FilmList extends Component {
constructor(...args) {
super(...args);
document.title = '艾米电影推荐';
this.stgId = localStorage.getItem("stgId") || "";
this.id = this.props.match.params.id;
this.state = {
listData: "",
page: 1,
pageSize: PS,
hasMore: false,
desc:'',
loading:true,
display:'none'
};
}
async componentWillMount() {
// console.log("片单ID-->", this.id);
await this.getList();
}
async getList(page=1) {
let url = `${PREFIX_URL}movie_client/list`+
`?stgId=${this.stgId}&movieListId=${this.id}&page=${page}&pageSize=${this.state.pageSize}`;
let res = await request(url);
if (res && res.success) {
document.title = res.title;
let listData = "";
if (page === 1) {
listData = res.data;
} else {
listData = this.state.listData;
listData = listData.concat(res.data);
}
await this.setState({
listData,
loading:false,
display:'block',
desc:res.desc,
page:res.page.current,
hasMore: res.page.current < res.page.pages
});
}
}
async componentWillUnmount () {
document.title = TITLE;
}
async refresh () {
await this.setState({page: 1});
await this.getList(1);
}
async loadMore() {
await this.setState({page: this.state.page + 1});
await this.getList(this.state.page);
}
render() {
return (
<div className="page-movie-detailed-list">
{
!!this.state.listData &&
<DetailedList
refresh={this.refresh.bind(this)}
loadMore={this.loadMore.bind(this)}
hasMore={this.state.hasMore}
listData={this.state.listData}
desc={this.state.desc}
style={{'display':this.state.display}}/>}
{this.state.loading ? <Loading/> : '' }
</div>
);
}
}

export default FilmList;

PC_demo

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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { Button, Col, message as Message, Row, Icon } from 'antd'
import { Link } from 'react-router-dom'
import React from 'react'
import MessageListFilter, { IMessageListFilter } from './components/MessageListFilter'
import MessageListTable from './components/MessageListTable'
import MessageService from '../../../service/driverManage/MessageService'

export default class MessageList extends React.Component {
// public constructor(props: any){
// super(props)
// }
public state = {
filterProps: {
filter: {
beginCreatedTime: '',
endCreatedTime: '', // 日期
sendStatus: '-1', //发送状态
},
},
tableProps: {
page: {
current: 1,
pageSize: 10,
total: 0,
},
data: [],
},
searching: false,
}

public componentDidMount() {
this.reSearch()
}

public filterChange = (params: IMessageListFilter) => {
this.setState({
filterProps: {
filter: {
...this.state.filterProps.filter,
...params,
},
},
})
}

public search = async () => {
this.setState({
searching: true,
})
const { code, message, data } = await MessageService.pageMessageList({
...this.state.filterProps.filter,
...{
sendStatus:
this.state.filterProps.filter.sendStatus !== '-1'
? this.state.filterProps.filter.sendStatus
: null,
},
pageNum: this.state.tableProps.page.current,
pageSize: this.state.tableProps.page.pageSize,
})
this.setState({
searching: false,
})
if (code !== 200) {
Message.error(message)
return
}
const { current, pageSize } = this.state.tableProps.page
let rows = []
rows =
data.rows && data.rows.length
? data.rows.map((item: any, index: number) => {
return {
...item,
num: (current - 1) * pageSize + index + 1,
}
})
: []
this.setState({
tableProps: {
page: {
...this.state.tableProps.page,
total: data.total,
},
data: rows,
},
})
}

public reSearch = () => {
const { tableProps } = this.state
const {
page: { pageSize, total },
} = tableProps

this.setState(
{
tableProps: {
...tableProps,
page: {
pageSize,
total,
current: 1,
},
},
},
() => {
this.search()
}
)
}

public pageChange = (page: object) => {
this.setState({
tableProps: {
...this.state.tableProps,
page,
},
})
this.search()
}

public getDetail = (params: any) => {
;(this.props as any).history.push('messageDetail', { id: 6, type: 0 })
}
public render() {
const { filterProps, tableProps, searching } = this.state
return (
<section>
<MessageListFilter
loading={searching}
{...filterProps}
onChange={this.filterChange}
onSearch={this.reSearch}
></MessageListFilter>
<Row style={{ marginBottom: '10px' }}>
<Col>
<Button type="primary">
<Link to={`/fast/message/messageCreate`}>
<Icon type="plus" />
<span style={{ marginLeft: '8px' }}>新建推送</span>
</Link>
</Button>
</Col>
</Row>
<MessageListTable
{...tableProps}
onPagechange={this.pageChange}
getDetail={this.getDetail}
onSearch={this.search}
loading={searching}
></MessageListTable>
</section>
)
}
}
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { Button, Table, Col, Modal, message as Message } from 'antd'
import React from 'react'
import { PaginationConf } from '../../../../config/antd/PaginationConf'
import { Link } from 'react-router-dom'
import MessageService from '../../../../service/driverManage/MessageService'
export interface IMessageTable {
num: string | number
creatTime: string
driverName: string
driverPhoneNum: string
receiptType: number
receipt: number | string
output: number | string
banace: number | string
}
export interface IProps {
data: IMessageTable[]
page: {
current: number
pageSize: number
total: number
}
onPagechange?: (page: { current: number; pageSize: number; total: number }) => void
getDetail: (param: any) => void
onSearch: () => void
loading: boolean
}

const { confirm } = Modal
class MessageListTable extends React.Component<IProps> {
public constructor(props: IProps) {
super(props)
;(this as any).columns = [
{
title: '序号',
dataIndex: 'num',
align: 'center',
},
{
title: '发送时间',
dataIndex: 'sendTime',
align: 'center',
},
{
title: '发送范围',
dataIndex: 'sendScope',
align: 'center',
},
{
title: '消息中心',
dataIndex: 'canIntoMessageCenter',
align: 'center',
},
{
title: '标题',
dataIndex: 'title',
align: 'center',
},
{
title: '操作人',
dataIndex: 'createdBy',
align: 'center',
},
{
title: '创建时间',
dataIndex: 'createdTime',
align: 'center',
},
{
title: '发送状态',
dataIndex: 'sendStatus',
align: 'center',
},
{
title: '操作',
align: 'center',
render(row: any) {
return (
<div>
{row.canCancelSend ? (
<Col>
<Button
type="primary"
onClick={() => {
cancel(row)
}}
>
取消发送
</Button>
{new Date(row.sendTime).getTime() - new Date().getTime() > 5 * 60 * 60 * 1000 ? (
<Button type="primary" style={{ marginLeft: '5px' }}>
<Link to={`/fast/message/messageUpdate/${row.id}`}>查看</Link>
</Button>
) : (
<Button type="primary" style={{ marginLeft: '5px' }}>
<Link to={`/fast/message/messageDetail/${row.id}`}>查看</Link>
</Button>
)}
</Col>
) : (
<Button type="primary">
<Link to={`/fast/message/messageDetail/${row.id}`}>查看</Link>
</Button>
)}
</div>
)
},
},
]
function cancel(row: any) {
const { onSearch } = props
if (new Date(row.sendTime).getTime() - new Date().getTime() > 5 * 60 * 60 * 1000) {
confirm({
title: '提示',
content: '是否确认取消',
async onOk() {
const { code, message } = await MessageService.messageCancel(row.id)
if (code !== 200) {
Message.error(message)
return
}
Message.success('取消成功')
onSearch()
},
onCancel() {
return
},
})
} else {
Modal.info({
title: '提示',
content: <div>距离预计发送时间不到5分钟 禁止取消</div>,
okText: '关闭',
})
}
}
}
public render() {
const { data, page, onPagechange, loading } = this.props
return (
<section>
<Table
dataSource={data}
loading={loading}
// @ts-ignore
columns={this.columns}
rowKey={'id'}
size={'middle'}
// scroll={{ x: 2500 }}
pagination={{
...PaginationConf,
...this.props.page,
onChange: (toCurrent, pageSize) => {
page.current = toCurrent
page.pageSize = pageSize as number

if (onPagechange) {
onPagechange(page)
}
},
onShowSizeChange: (current, toPageSize) => {
page.current = current
page.pageSize = toPageSize

if (onPagechange) {
onPagechange(page)
}
},
showTotal: (total: number) => `共计 ${total} 条`,
}}
></Table>
</section>
)
}
}

export { MessageListTable }
export default MessageListTable