我正在尝试遍历数组并将结果推入数组,但数组返回为空

const actionOpportunities = result.data.opportunities
const actionArray = []


for (let opportunities of actionOpportunities){
  const currentIDs = opportunities.id
  axios.get('apiURL.com='+currentIDs,clientGet)
  .then((results)=>{
    const actionsResult = results.data.actions

    actionArray.push(actionsResult)
  })
}

console.log(actionArray)

最佳答案

这是因为actionArray.push将在以后执行。 Axios返回一个Promise,在传递给thenactionArray回调之后,将执行该传递。

解决方案:等待所有承诺解决,您可以使用console.log(actionArray),此时您可以收集所有结果。

类似于以下内容:

const promises = []
for (let opportunities of actionOpportunities){
  const currentIDs = opportunities.id
  promises.push(axios.get('apiURL.com='+currentIDs, clientGet))
}

Promise.all(promises).then(allResults => {
  console.log(allResults)
})

09-30 13:18