转向Axios发布请求答应循环

时间:2019-03-29 18:30:08

标签: javascript reactjs post axios

我有一个axios请求循环:

for(const [number, response] of Object.entries(questions)){
  axios.post(
    this.address+'surveypost',
     {"patientID": patientID,
              "questionID": number,
                "likertResponse": response,
                  "surveyNumber": surveyID, "admin": this.admin, "masterpassword": this.masterpassword},
    { headers: {'Content-Type': 'application/json'} }
  )
    .then(e =>{console.log(e);
    console.log("inserted")})
    .catch(error =>{console.log(error)})
}

,我需要将它们变成一个axios承诺。我将如何处理该问题,以便我能兑现承诺,确保一切都已完成?

我想要的输出是return promise(...)或类似的东西,因为在以下情况中我需要做一些后续操作:

var chain = Promise.resolve() .then(promise) // LOOPED AXIOS POST REQUEST ABOVE .then(another_promise) // subsequent actions;

1 个答案:

答案 0 :(得分:0)

您可以将每个promise推送到数组,然后调用Promise.all

let promsArr = [];
for(const [number, response] of Object.entries(questions)){
  promsArr.push(axios.post(
    this.address+'surveypost',
     {"patientID": patientID,
              "questionID": number,
                "likertResponse": response,
                  "surveyNumber": surveyID, "admin": this.admin, "masterpassword": this.masterpassword},
    { headers: {'Content-Type': 'application/json'} }
  ))
}

Promise.all(promsArr)
.then(resp => {
  console.log("data", resp);
})
.catch(err => {console.log(err)})
相关问题