let saveMsg = [];
const ajax = (url,i) => {
var p = new Promise((resolve, reject) => {
var random = Math.round(Math.random() * 9) + 1
setTimeout(() => {
if (random > 5) {
console.log(`第${i}轮循环,${url}请求成功`)
resolve({ url, code: 0 })
} else {
console.log(`第${i}轮循环,${url}请求失败`)
reject({ url, code: -1 })
}
}, random * 100)
})
return p
}
const pfn = async (i) => {
return ajax('req1', i)
.then(res => ajax('req2', i))
.then(res => ajax('req3', i))
.catch(err => {
console.log(i, err)
saveMsg.push({index: i, err})
})
}
async function batchReq () {
//遍历5次,每次分别请求3个接口,如果第1接口失败,后面2个接口停止执行
for (let i = 0; i < 5; i++) {
await pfn(i)
}
}
async function main () {
await batchReq()
console.log('alert', JSON.stringify(saveMsg, null, 2))
}
main()
console