Troubleshooting Async Await functionality with Cloudinary in JavaScript

My current issue involves using Cloudinary to upload an image and then sending the returned URL from Cloudinary to the backend for storage in my database. The problem arises when calling the Cloudinary API, as it does not wait for the response before proceeding to call the backend URL. I have attempted solutions such as async-await and promises, but nothing seems to be working.

Here is the code snippet from 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
    }
}

And from 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)
    })
}

Answer №1

Ensure that your promises are correctly linked together. It is not advisable to combine async/await and then. Additionally, make sure the image URL parameter is defined; otherwise, the backend will not receive the image URL.

Answer №2

Instead of using res.json(), you can utilize it with the fetch function. When working with axios, there is no need for that extra step. Additionally, you do not require the use of async / await in your initial function.

import axios from "axios"
export default {
  uploadToCloudinary(data) {
    let url = `url`;
    let config = {
      headers: {
        "Content-type": "multipart/form-data",
      },
    };
    return axios.post(url, data, config).then((res) => res.data.secure_url);
  },
};




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

    let imageUrl = await cloudinary.uploadToCloudinary(formy);

    let response = await dataService.sendToDatabase({
      image: imageUrl.secure_url,
    });

    console.log(response);
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing two select fields in a dynamic Angular form - best practices

On my screen, I am dynamically creating elements using a reactive form. Specifically, I am creating cards with two selection fields each: https://i.sstatic.net/WUvQH.png Situation: When I add a card and choose a layout, the options for that specific layo ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Utilize AJAX and jQuery to seamlessly submit a form

I am attempting to use jQuery and AJAX to submit a form in order to add a row to a table called cadreSante (which is in French). The code I am using for this operation is provided below. Can someone please identify any errors in the code and suggest ways t ...

Laravel 4 Data Cleaning for Improved Security

I am currently utilizing Laravel 4 to establish a RESTful interface for my AngularJS application. Right now, I am looking to update an object within my model named Discount Link. The method I am using involves: $data = Input::all(); $affectedRows ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: https://i.sstatic.net/Y10X7.png The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').Data ...

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

When tab switching occurs, the alert box fails to be processed by the browser

When using the alert(message) function, it will display an alert box with a message and an OK button. It will also pause the execution of any code that follows until the OK button is clicked. However, I have noticed a peculiar situation where switching tab ...

Which Client-Side JavaScript Frameworks Pair Seamlessly With Node.js, Express.js, and socket.io.js?

Currently, I am in the process of developing a web application utilizing Node.js, Express.js, and socket.io.js on the server side. Are there any front-end frameworks (such as Agility, Angular, Backbone, Closure, Dojo, Ember, GWT, jQuery, Knockback, Knocko ...

Assigning a value to a JavaScript variable using Ajax

Struggling with a problem for hours and still can't find the issue... A registration form is set up for users to create accounts. When the submit button is clicked, a validateForm function is triggered. Within this function, some JavaScript tests ar ...

Electron generates a unique landing page for your first launch

Can you help me create a feature on a webpage that only appears once and then never shows again? Similar to the "Never show me again" checkbox in Visual Studio Code upon first launch. ...

Saving Arrays through an Input Form in JavaScript

I am working with an HTML form that looks like the following: <div class="form-group"> <label for="first_name">1st Name</label> <input type="text" id="first_name" placeholder="First Name" class="form-control"/> </div> ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...

Ways to access the values of checkboxes that are initially checked by default

Recently, I was working on a project that involved multiple checkboxes. My goal was to have the checkboxes pre-checked with values in the form (using reactive form). Users should be able to unselect the boxes as they wish and the data would be stored accor ...

naming a function on a global scale

Looking for a JavaScript function f that can take an anonymous function g and a name n, and assign g to that name in the global scope or current scope. The function should be usable in this way: f(function(){ /* code */ }, "foo"); foo(); // this call sho ...

Perform a fetch request within a map function or loop

I'm currently working on iterating over an array of objects. Depending on the content of some of those objects, I need to execute a fetch function and wait for the result before updating the new array. Below is my JavaScript code: const allPosts = ...

unable to load variables in google extension due to technical difficulties

I'm encountering an error even though I've already loaded the DOM. I have no idea how to fix this issue and I've been sitting here for hours trying to troubleshoot. The error message I'm getting is: btncheck.js:10 Uncaught TypeError: C ...

How can JavaScript generate arrays filled with randomly generated numbers?

As part of a classroom assignment, I am working on creating a table using only Javascript. The table is set up perfectly, except that every other row displays a random number before moving on to the next row. How can I eliminate this random row? var ta ...

Is there a way to ensure that a "loop once" animated GIF background will replay on each page refresh or load?

I currently have an animated GIF file set as the background image for my div, which was specifically configured in Photoshop to loop only once. Therefore, it only plays on the initial page load. Is there a way to reset the background image upon page refre ...

The readAsDataURL method generates an invalid Base64 string for PNG images, while it works properly for JPG/JPEG files

Dealing with a React Native app and attempting to address this particular problem. The base64 is sent to an API and saved in the database as a blob. I understand that it's not ideal practice, but given that this is just a simple student project and no ...