消除`axios`嵌套调用中的竞争条件

时间:2018-01-07 23:56:55

标签: reactjs axios

使用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
    });
});

outerCallinnerCall都执行axios.get(...)(位于rest文件内)。在setState()执行之前执行innerCall。如何在setState完成之前等待innerCall

1 个答案:

答案 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()