【问题标题】:Turn for loop of Axios post requests to promise转for循环的axios post requests to promise
【发布时间】:2019-03-29 18:30:08
【问题描述】:

我有一个 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;

【问题讨论】:

  • 使用 Promise.all

标签: javascript reactjs post axios


【解决方案1】:

您可以将每个承诺推送到一个数组并调用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)})

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2019-10-11
    • 2023-04-06
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    相关资源
    最近更新 更多