使用axios
消除API请求中的竞争条件有什么好方法?我有这个:
rest.outerCall(id).then(results => {
let {data} = results;
for (let i = 0; i < data.length; i++) {
rest.innerCall(data[i].id).then(innerData => {
data[i].name = innerData.name;
});
}
this.setState({
results: results.data
});
});
outerCall
和innerCall
都执行axios.get(...)
(位于rest
文件内)。在setState()
执行之前执行innerCall
。如何在setState
完成之前等待innerCall
?
答案 0 :(得分:0)
你是probs想要利用Promise.all()
的内容。
请参阅下面的实例。
// Outer Call.
const outercall = (id) => {
return new Promise((resolve, reject) => {
return setTimeout(() => {
console.log('outercall', time())
return resolve({data: ['1', '2', '3', '4']})
}, 1000)
})
}
// Inner Call.
const innercall = (id) => {
return new Promise((resolve, reject) => {
return setTimeout(() => {
console.log(`innercall: ${id}`, time())
return resolve(`innercall: ${id}`)
}, 5000)
})
}
// Set State.
const setState = (state) => console.log('setState', state)
// Run.
const run = () => {
// State.
console.log('start', time())
// Outer Call.
outercall().then(({data}) => {
// Inner Call Requests.
const requests = data.map(innercall)
// Execute each using Promise.all().
Promise.all(requests).then((result) => {
// Set State.
setState({result})
})
})
}
// Time.
const time = () => new Date() * 1
// Run.
run()