简体   繁体   English

如何在react js中的循环和条件语句中进行异步api调用?

[英]How to make asynchronous api calls in loop and conditional statements in react js?

[
  {
    description: "question value1",
    subjectId: "",
    classId: "",
    image:"",
    answers: [{ description: "option value", isCorrect: false },
    { description: "option value", isCorrect: true }
    ],
  },
  {
    description: "question value2",
    subjectId: "",
    classId: "",
    answers: [{ description: "option value", isCorrect: false },
    { description: "option value", isCorrect: true }
    ],
  },
]

I have something like this and now i need to make the post call to api for each question so that once the question is created i get the question ID back and then i can use that ID to create options for that question and if it has image upload the image too and have to wait for each of them to finish how can i do that i really m bad asynchronous progamming, there are sperate API's for creating a question creating a option for the question uploading a image for the question This what i have tried so far but for some reason its wrong idk我有这样的事情,现在我需要为每个问题对 api 进行 post 调用,这样一旦问题被创建,我就会得到问题 ID,然后我可以使用该 ID 为该问题创建选项,如果它有图像也上传图像并且必须等待他们每个人完成我该怎么做我真的很糟糕异步编程,有一些用于创建问题的API为问题创建选项为问题上传图像这就是我所拥有的到目前为止尝试过但由于某种原因它的 idk 错误

    async mapCreatedQuestions(questionId) {
    let token = getCookie(process.env.token);
    let formData = new FormData();
    formData.append("QuestionId", questionId);
    formData.append("QuizId", this.state.quizId);
   await axios
      .post(`api to create a association if question already exists`, formData, {
        headers: {
          authorization: `${TOKEN_TYPE}${token}`,
        },
      })
      .then((response) => {})
      .catch((err) => {
        console.log("Error !!!.. association");
        console.log(err);
        this.setState({ loading: false });
      });
  }
  async createOptions(question, questionId) {
    let token = getCookie(process.env.token);
    question.answers.map((option, index) => {
      //options uploaded from here
      console.log("this options are for the question", option);
      if (option.description.length > 0) {
        let formData = new FormData();
        formData.append("Description", option.description);
        formData.append("QuestionId", questionId);
        formData.append("IsCorrect", option.isCorrect);
        axios
          .post(`api to add answers(options)`, formData, {
            headers: {
              authorization: `${TOKEN_TYPE}${token}`,
            },
          })
          .then((response) => {
            console.log("option created", response);
          })
          .catch((err) => {
            console.log("Error !!!.. In options");
            console.log(err);
            this.setState({ loading: false });
          });
      }
    });
  }
  async questionImageUpload(questionPicture, questionId) {
    let token = getCookie(process.env.token);
    //upload the picture of the question

    let formData = new FormData();
    formData.append("ImageTitle", "quizImage" + questionId);
    formData.append("QuestionId", questionId);
    formData.append("Image", questionPicture);
  await  axios
      .post(`api to upload image`, formData, {
        headers: {
          authorization: `${TOKEN_TYPE}${token}`,
        },
      })
      .then((response) => {
        console.log("image uploaded successfully ", response);
      })
      .catch((err) => {
        console.log(" image upload failed err", err);
        this.setState({ loading: false });
      });
  }
 async createEachQuestion (question){
   let formData = new FormData();
   formData.append("Description", question.description);
   formData.append("QuestionTypeId", question.questionTypeId);
   formData.append("SubjectId", question.subjectId);
  await axios
     .post(`apitocreatequestion`, formData, {
       headers: {
         authorization: `${TOKEN_TYPE}${token}`,
       },
     })
     .then((response) => {
       this.setState({ questionId: response.data.result });
       let questionId = response.data.result;
       if (question.questionPicture.toString().length > 0) {
        this.questionImageUpload(question.questionPicture, questionId);
       }
     })
     .catch((err) => {
       console.log("error in question creationn", err);
     });
      await this.createOptions(question,questionId);
     await this.mapCreatedQuestions(questionId);

 } 
 async mapEachQuestion (){
  console.log("this question will be mapped not created", question);
  let formData = new FormData();
  formData.append("QuestionId", question.questionId);
  formData.append("QuizId", this.state.quizId);
 await axios
    .post(`apitoassociatequestionandquiz`, formData, {
      headers: {
        authorization: `${TOKEN_TYPE}${token}`,
      },
    })
    .then((response) => {
      console.log("question asssociated", response);
    })
    .catch((err) => {
      console.log("Error !!!.. association");
      console.log(err);
      this.setState({ loading: false });
    });
 }
  async createQuestion() {
    let token = getCookie(process.env.token);
    this.state.questionList.map((question, index) => {
      if (question.hasOwnProperty("questionId")) {
        //map the existing question id to quiz
        this.mapEachQuestion (question)
      } else {
        this.createEachQuestion (question)
      }
    });
  }

  async createQuiz(quiz) {
    await this.setQuestionList;
    await this.sendQuiz;
    this.setState({ loading: true });
    let formData = new FormData();
    console.log("quiz", quiz);
    console.log("this.state.questionList", this.state.questionList);
    let id = getCookie(process.env.iId);
    formData.append("Description", quiz.Description);
    formData.append("Title", quiz.Title);
    formData.append("TimeinMinute", quiz.TimeInMinute);
    let token = getCookie(process.env.token);
    await axios
      .post(`apitocreatequiz`, formData, {
        headers: {
          authorization: `${TOKEN_TYPE}${token}`,
        },
      })
      .then((response) => {
        console.log("quiz created successfully. Response =>", response);
        //setQuizId in state
        this.setState({ quizId: response.data.result });
        
      })
      .catch((err) => {
        console.log("Error !!!.. when creating the quiz");
        console.log(err);
        this.setState({loading:false});
      });
      await this.createQuestion;
      this.setState({loading: false});
  }

API calls are a promise that data will be returned at some point . API 调用是对数据将在某个时间返回的承诺

Fortunately async processes have become much easier to deal with recently.幸运的是,异步进程最近变得更容易处理。 You can use Promise.all to capture the data once it's been resolved.一旦数据得到解决,您可以使用Promise.all来捕获数据。

Your data is already in an array so it becomes much easier.您的数据已经在一个数组中,因此它变得更加容易。

In this first example you can use the Fetch API to get the data, and then gather the data.在第一个示例中,您可以使用Fetch API来获取数据,然后收集数据。

 function mockApi(n) { return new Promise((res, rej) => { setTimeout(() => res(n), 2000); }); } const input = [1, 2, 3, 4]; function getData(input) { // Instead of mockApi(el) use `fetch(url)` const promises = input.map(el => mockApi(el)); Promise.all(promises).then(data => { console.log(data); }); } getData(input);

In this example you can use async/await :在这个例子中,你可以使用async/await

function mockApi(n) {
  return new Promise((res, rej) => {
    setTimeout(() => res(n), 2000);
  });
}

const input = [1, 2, 3, 4];

async function getData(input) {
  const data = input.map(el => mockApi(el));
  const output = await Promise.all(data);
  console.log(output);
}

getData(input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM