<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quequ</title>
</head>
<body>
<script>
class Quequ {
store = []
results = []
flag = false
callback = function() {}
push(fns, callback) {
if(callback && callback instanceof Function) this.callback = callback
if (Array.isArray(fns)) {
fns.forEach(fn => {
this.store.push(fn)
})
} else if (fns instanceof Function) {
this.store.push(fns)
} else {
console.error('Arguments must be Array or Function')
return
}
this.start()
}
async do(retryFn) {
let fn = retryFn? retryFn: this.store.shift()
try {
let res = await fn()
this.results.push({ name, value: res, error: null })
if (this.store.length) {
return this.do()
}
} catch(err) {
let errMsg = err.message || err
console.error(`${name} exec error, ` + errMsg)
if (!fn._retrytime) fn._retrytime = 0
if (fn._retrytime < 3) {
fn._retrytime++
return this.do(fn)
} else {
delete fn._retrytime
this.results.push({ name, value: null, error: errMsg })
}
}
}
async start(retryFn) {
if(this.flag || !this.store.length) return
this.flag = true
await this.do()
this.callback(this.results)
this.flag = false
this.results = []
this.callback = function() {}
}
empty() {
return !this.store.length
}
results() {
return this.results
}
}
let fn1 = () =>{
return new Promise((r, j) => {
setTimeout(() => {
console.log('fn1')
r('fn1')
}, 1000)
})
}
let fn2 = () => {
return new Promise((r, j) => {
setTimeout(() => {
console.log('fn2')
r('fn2')
}, 1000)
})
}
let fn3 = () => {
return new Promise((r, j) => {
setTimeout(() => {
console.log('fn3')
j('fn3')
}, 1000)
})
}
let quequ = new Quequ()
quequ.push([fn1, fn2], (results) => {
console.log(results)
})
quequ.push(fn3, (results) => {
console.log(1111, results)
})
</script>
</body>
</html>