简体   繁体   中英

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

    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 .

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.

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.

 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 :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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