背景
项目中,一个列表项的数据,需要调两个接口去拼接,先调a接口,拿接口返回去调用b。考虑第二次接口请求只是简单取一个字符串来展示,先写了循环调用保证基本功能,后续用Promise.all重写。
代码实现
<script>
export default {
data() {
return {
//第一次请求得来的数据 id作为入参做二次请求
listArr: [{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }, { id: 'e' }],
};
},
methods: {
getMore(id) {
//用定时器和随机数 模拟接口调用
return new Promise((resolve) => {
setTimeout(function () {
resolve(id)
}, Math.random() * 1000)
})
},
},
mounted() {
let vm = this
let promises = this.listArr.map(function (item) {
return vm.getMore('/post/' + item.id + '.json')
})
try {
Promise.all(promises).then(res => {
//虽然接口耗时不同 但promise.all 顺序依然是链式调用
window.console.log(res)
}).catch(err => {
window.console.log(err)
})
} catch (error) {
window.console.log(error)
}
}
};
</script>
chrome打印
总结
相比直接js循环二次调用,promise.all的写法,能更方便的处理返回结果,以及保证调用顺序