Как я могу заставить метод ждать другого метода до конца sh? - PullRequest
0 голосов
/ 17 января 2020

У меня есть следующий метод в React, и я хотел бы завершить первые два метода, которые загружают изображения в cloudinary и устанавливают URL-адрес в состояние, закодированное в первую очередь, перед выполнением вызова API addStudent, поскольку необходимо передать значения состояния обновления на.

Код ниже и предполагаемый порядок в комментариях. В настоящее время, если я смотрю на Сеть в инструментах разработчика, она выполняется в правильном порядке, но последний вызов API addStudent, похоже, не ожидает, пока setState не выполнятся в предыдущих методах, так как происходит сбой с данными base64.

Как я могу изменить приведенный ниже код для достижения необходимого заказа?

addStudent= e => {
  this.setState({step:0})  //renders a loading screen

  const files1 = Array.from(this.state.profilePic)
  const formData1 = new FormData()
  files1.forEach((file, i) => {
    formData1.append(i, file)}) 

  const files2 = Array.of(this.state.passportPhoto)
  const formData2 = new FormData()
  files2.forEach((file, i) => {
    formData2.append(i, file)})


//uploads profilePic to cloudinary and sets state to URL returned by the api call --> order 1
    fetch(`http://localhost:3030/image-upload`, {method: 'POST',body: formData1})
      .then(res => res.json())
      .then(images1 => {this.setState({profilePic: images1[0].url})})


//upload passportPic to cloudinary and sets state to URL returned by the api call --> order 2
      .then(fetch(`http://localhost:3030/imageUploadPassport`, {method: 'POST',body: formData2})
      .then(res => res.json())
      .then(images2 => {this.setState({passportPhoto: images2[0].url})})

//uses data in state objects above to enter data to SQL database  --> order 3
      .then(fetch(`http://localhost:3030/addStudent?profPicURL=${this.state.profilePic}&passportURL=${this.state.passportPhoto}`)
      .catch(err=>console.error(err))
      .then(this.setState({step:2008}))))   //displays a success screen

  }

Ответы [ 2 ]

0 голосов
/ 17 января 2020

Использование Javascript Обещает дождаться асинхронных функций.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

0 голосов
/ 17 января 2020

addStudent= async e => {
  this.setState({step:0})  //renders a loading screen

  const files1 = Array.from(this.state.profilePic)
  const formData1 = new FormData()
  files1.forEach((file, i) => {
    formData1.append(i, file)}) 

  const files2 = Array.of(this.state.passportPhoto)
  const formData2 = new FormData()
  files2.forEach((file, i) => {
    formData2.append(i, file)})

  const data1 = await fetch('http://localhost:3030/image-upload', {method: 'POST',body: formData1});
  const image1 = await data1.json();
  
  const data2 = await fetch('http://localhost:3030/imageUploadPassport', {method: 'POST',body: formData2});
  const image2 = await data2.json();
  
  
  const data3 = await fetch(`http://localhost:3030/addStudent?profPicURL=${image1[0].url}&passportURL=${image2[0].url}`);
  
  this.setState({step:2008});

  }
...