- 在vue中循环调用接口-promise.all()
methods: {
handleAdd (arr) {
this.loading = true
const allApi = []
arr.forEach((item, index) => {
const data = {
id: item.id,
name: item.name
}
const oneApi = api.add(data).then(res => {
if (res.error_code === 0) {
this.$message.success(res.msg)
} else {
this.$message.error(res.msg)
}
})
allApi.push(oneApi)
})
Promise.all(allApi).then(() => {
this.loading = false
})
}
}
- 有异步处理数据时,按顺序执行函数
methods: {
handleAdd (val) {
this.addTag(val).then(() => {
this.tags.push(this.newTag)
this.editNote()
})
},
addTag (val) {
const data = {
tag: val
}
return add(data).then(res => {
this.newTag = {
id: res.data.id,
name: res.data.name
}
})
},
editNote () {
const data = {
tags: this.tags,
}
update(data).then((res) => {
if (res.error_code === 0) {
this.$message.success('修改成功!')
}
})
}
}
使用return返回第一个异步处理的结果;使用then,继续执行第二个异步处理(当第一次返回结果为ture时)。