Home > Back-end >  Async Await not working on cloudinary - Javascript
Async Await not working on cloudinary - Javascript

Time:05-20

I am using cloudinary to upload the image and after the image url is returned from cloudinary, I want to send the url to backend and save it in my database. The problem is when i call using the cloudinary api, it is not waiting for the response to come back from cloudinary, it staright away goes to hit the backend url after the cloudinary one. I have used async await and promise also. But it is not working.

cloudinary.js

import axios from 'axios'

export default {
async uploadToCloudinary(data) {
    

    let url = `url`

    let config = {
        headers: {
            "Content-type": "multipart/form-data",
        },
    };

    let image_url = axios.post(url, data, config).then(async res => {
        let data = await res.json();
        return data.secure_url
    }).catch(error => {
        console.log(error)

    })

    return image_url
}
}

main.vue

    async process() {

  let formy = new FormData();
  formy.append("file", this.file);
  formy.append("upload_preset", 'abcde');

 let imageUrl = await cloudinary.uploadToCloudinary(formy)

  await dataService.sendToDatabase({ image: imageUrl.secure_url}).then(res => {
    console.log(res)
  })

}

CodePudding user response:

The usage of async await looks to be wrong. Can't mix async await and the promise then function in the same function. For your clarity I'll add two ways you can solve the problem

Correct way:

import axios from "axios";

export default {
  async uploadToCloudinary(data) {
    let url = `url`;

    let config = {
      headers: {
        "Content-type": "multipart/form-data",
      },
    };

    try {
        let res = await axios.post(url, data, config);
        let data = await res.json();
        return data.secure_url;
    } catch(error) {
        return error;
    }
  },
};

Another way to help you understand async/await (Do not use this):

import axios from "axios";

export default {
  async uploadToCloudinary(data) {
    let url = `url`;

    let config = {
      headers: {
        "Content-type": "multipart/form-data",
      },
    };

    let image_url = await new Promise((resolve, reject) => {
        axios
        .post(url, data, config)
        .then(async (res) => {
          let data = await res.json();
          resolve(data.secure_url);
        })
        .catch((error) => {
          reject(error);
        });
    })
    

    return image_url;
  },
};

CodePudding user response:

My guess is that your code is actually working as expected, but you're sending the wrong data to the database: instead of sending imageUrl.secure_url you need to send imageUrl because uploadToCloudinary is already returning the secure URL (return data.secure_url).

  • Related