使用async/await 或 Promise.all 方法等来解决并行获取所产生的竞态条件问题。代码示例:
使用async/await:
async function fetchData() {
const response1 = await fetch('url1')
const data1 = await response1.json()
const response2 = await fetch('url2')
const data2 = await response2.json()
// ...
}
使用Promise.all:
async function fetchData() {
const [data1, data2] = await Promise.all([
fetch('url1').then(response => response.json()),
fetch('url2').then(response => response.json())
])
// ...
}