0%

前端技术整理——Promise

Promise

应用题:(模仿promise.all())定一个函数,参数为一个需要异步操作的URL数组,需要返回一个Promise格式的结果——假如所有异步操作成功,则返回所有成功后结果集合;假如其中有异步操作失败,则返回失败的信息

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
testPromise (requests = [], results = []) {
return new Promise((resolve, reject) => {
let count = 0
requests.forEach((request) => {
new Promise((resolve, reject) => {
const timeOut = request
// var timeOut = Math.random() * 2
console.log('----start new Promise...timeout to: ' + timeOut + ' seconds.')
setTimeout(function () {
if (timeOut < 1) {
console.log('-----call resolve()...')
resolve('-----200 OK')
} else {
console.log('-----call reject()...')
reject(new Error('==timeout==' + timeOut + 'seconds'))
}
}, timeOut * 1000)
}).then((success) => {
count += 1
results.push(request)
if (count === requests.length) {
console.log('test----call all resolve()...!!!')
resolve(results)
}
}).catch((err) => {
reject(err)
})
})
})
}

// 函数使用案例
this.testPromise([0.1, 0.4, 0.5, 0.3, 1.7, 0.7])
.then((res) => console.log('=====success==== ', res))
.catch((err) => console.log('=====error==== ', err))