Home > Net >  Vue : How to use async await accordingly in a function array of which can have two functions for Pro
Vue : How to use async await accordingly in a function array of which can have two functions for Pro

Time:12-15

I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?

1.vue

<template>
  <div>
    <label for="imgUpload">
      <button >upload</button>
    </label>
    <input
      type="file"
      
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo')"
    />
    <div v-if="imageData" >
      <img :src="imageData" />
    </div>

    <label for="imgUpload">
      <button >upload1</button>
    </label>
    <input
      type="file"
      
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo1')"
    />
    <div v-if="imageData1" >
      <img :src="imageData1" />
    </div>
    <button @click="useFunctionToAllServers">BUTTON</button>
  </div>
</template>
<script>
import {
  updateGeneralInfo,
  createUploadToOther,
  updateGeneralInfoToOther,
} from '@/2'

export default {
  data() {
    return {
      filename: '',
      filename1: '',
      originalFilename: '',
      originalFilename1: '',
      imageData: '',
      imageData1: '',
      serverNames: ['a server', 'b server'],
      idxs: [0, 1],
      serverFullAddress:['http://a.url', 'http://b.url'],
      serverResCheck:[],
      isLogoChanged:false,
      isLogo1Changed:false,
    }
  },
  methods: {  
    sendFile(type) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
      } else {
        file = this.$refs.logo1.files[0]
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        if (type == 'logo') {
        this.imageData = e.target.result
        } else {
        this.imageData1 = e.target.result
        }
      }
    },
    sendFileToOther(type, serverFullURL) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
        this.originalFilename = this.$refs.logo.files[0].name
      } else {
        file = this.$refs.logo1.files[0]
        this.originalFilename1 = this.$refs.logo1.files[0].name
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const formdata = new FormData()
      formdata.append('logo', file)
      
      formdata.append('serverURL', serverFullURL)

      return createUploadToOther(formdata)
    },
    
    async useFunctionToAllServers() {
      
        let data = {
          foo: this.foo,
          bar: this.bar,
        }
        
        await updateGeneralInfo(data).then().catch()
      
        await Promise.all(this.submitToTheOthers()).catch((err) =>{ // [Promise.all]
          console.log('Promise.all err>>', err)
        });  
        
        let notWorkingServers = []
        for(let i=0; i< this.idxs.length ; i  ){
          if(!this.serverResCheck[i]){
          notWorkingServers.push(this.serverNames[i])
          }
        }
        if(Array.isArray(notWorkingServers) && notWorkingServers.length == 0){
          alert('not working : ', notWorkingServers)
        }else{
          alert('all server works')
        }      
    },
    submitToTheOthers(){
      let data = {
        foo: this.foo,
        bar: this.bar,
      }
      let logoData ={}
      if(this.originalFilename){
        data.logo = this.originalFilename
        logoData.logo = true
      }else if(this.isLogoChanged){
        data.logo = this.logo
      }
      if(this.originalFilename1){
        data.logo1 = this.originalFilename1
        logoData.logo1 = true
      }else if(this.isLogo1Changed){
        data.logo1 = this.logo1
      }
      
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => { // [here2]
          if (res.status == 200) {
            this.serverResCheck[i] = true
            if(logoData.logo){
              this.sendFileToOther('logo', this.serverFullAddress[i]).then((res) => { // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
            if(logoData.logo1){
              this.sendFileToOther('logo1', this.serverFullAddress[i]).then((res) =>{ // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
          }else{
            this.serverResCheck[i] = false            
          }
        }).catch((err) => {
          this.serverResCheck[i] = false
        })
      })
    },
  },
}
</script>

2.js

import axios from 'axios'
export const headers = {
  'Content-Type': 'application/json',
  'header1' : 'header1',
  'header2' : 'header2',
}

export function updateGeneralInfoToOther(id, data, serverAddress) {
  data.serverAddress = serverAddress
  return axios.put(`/u/r/l/${id}`, data, { headers })
}

export function updateGeneralInfo(id, data) {
  return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}

export function createUploadToOther(data) {
  return axios.post('/u/r/l', data, { headers })
}

CodePudding user response:

To use await in those callbacks, each callback function itself needs to be async:

export default {
  methods: {
    submitToTheOthers(){
      ⋮
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then(async (res) => { // [here2]
            ✅                                                                                
  • Related