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))
|