Requirements introduction:
Vue loops to request the same interface, and then proceeds to the next loop after the interface returns data (in projects, sometimes batch operations are required, and some more special interfaces need to be called in order.)
Points to note: (10 tasks are delivered in batches, delivered in order of task numbers, and at the same time need to wait for the delivery of the previous task to be completed before delivering the next task (otherwise there may be later interfaces that execute faster and deliver in advance Condition))
code show as below:
// 批量下发
multipleIssue() {
const arr = [123, 456, ...id]
var that = this // 改变this指向
function callPromise(item) {
return new Promise((resolve, reject) => {
testInterface({
id: item }).then((res) => {
if (res.status) {
that.$message({
// 方法内部用that替代this
message: '下发成功',
type: 'success'
})
resolve(item)
} else {
that.$message.error(res.msg)
}
})
})
}
const result = arr.reduce((accumulatorPromise, next) => {
return accumulatorPromise.then(() => {
// 上一个接口执行完毕再执行下一个
return callPromise(next)
})
}, Promise.resolve())
result.then(e => {
console.log('All Promises Resolved')
})
}
Reference article: Five ways to use async/await in loops
Requirement two:
How does vue loop to request the same interface ten times, wait for the first request to complete, then request the second one, and so on... If the tenth request fails, wait for three seconds to re-initiate the request?
function request(){
return new Promise((res, rej) => {
setTimeout(() => {
Math.random() > 0.5 ? res() : rej()
}, Math.random() * 1000 + 1000)
})
}
function loop(){
let flag = false
let p = Promise.resolve()
for(let i = 0; i < 10; i++){
p = p.then(_ => {
return request().then(_ => {
flag = true
}, err => {
})
})
}
p.then(_ => {
flag || setTimeout(loop, 3000)
})
}