All promises in the Promise.all() function are resolved instantaneously

I am currently attempting to execute a series of actions after uploading multiple images, utilizing Promise.all.

However, I have noticed that the code following the then statement is running before the dispatched code.

Where am I going wrong in my understanding?

  submit_all_images({ dispatch, rootState }) {
    const imageFileArray = rootState.imageStore.imageFileArray 
    var promiseArray = []

    for ( var imageFile of imageFileArray ) {
      promiseArray.push(dispatch('get_signed_request', imageFile))
    }

    Promise.all(promiseArray)
      .then(results => {
        console.log("completed with results: " + results)
        return dispatch('submit_entire_form')
      });
  },
  get_signed_request ({ dispatch, commit, state }, imgFile) {
    const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
    axios.post('http://localhost:3000/sign-s3', requestObject)
    .then(response => {
        if (response.body.signedRequest && response.body.awsImageUrl) {
          const signedRequest = response.body.signedRequest
          const awsImageUrl = response.body.awsImageUrl
          dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
        } else {
          alert('Could not obtain signed URL.');
        }
    }, error => {
      console.log("ERROR: " + error)
    })
  },

  upload_file ({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }) {
    axios.put(signedRequest, imgFile, {
      headers: {'Content-Type': imgFile.type}
    }).then(response => {
      console.log('file uploaded successfully: ' + imgFile.name )
      commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
    }, error => {
      alert("failure")
      console.log(error)
    })
  },

Answer №1

I'm unsure about this as I haven't worked with vuex before, but it seems like there might be a need for additional return statements in your code.

get_signed_request({ dispatch, commit, state }, imgFile){
    const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
    //you may need to add a return statement here
    return axios.post('http://localhost:3000/sign-s3', requestObject)
        .then(response => {
            if (response.body.signedRequest && response.body.awsImageUrl) {
                const signedRequest = response.body.signedRequest
                const awsImageUrl = response.body.awsImageUrl
                //consider adding a return statement here
                return dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
            } else {
                alert('Could not get signed URL.');
            }
        }, error => {
            console.log("ERROR: " + error)
        })
},

upload_file({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }){
    //you may need to add a return statement here
    return axios.put(signedRequest, imgFile, {
        headers: {'Content-Type': imgFile.type}
    }).then(response => {
        console.log('finished uploading file: ' + imgFile.name )
        //adding a potential return statement here
        return commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
    }, error => {
        alert("fail")
        console.log(error)
    })
},

It's important that the get_signed_request function returns a Promise that resolves only after axios.post().then() has completed and depends on resolving dispatch('upload_file', ...)

Similarly, upload_file should also return a Promise that depends on the completion of axios.put().then()and

commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)

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

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Please ensure there is space reserved for the header above the content

Currently, I am working on creating a webpage with a unique banner design. My goal is for the content to scroll from the bottom and remain fixed directly under the upper portion of the banner. Initially, my idea was to have the content box take up the siz ...

How can you display directions while using the Google Maps app in a React Native application?

I need assistance with rendering directions between two points (current location and a passed location). Currently, I am using Linking to open the Google Maps App. However, when clicking the button passing the (latitude, longitude), I want the map to disp ...

I am looking to dynamically fill my form fields with data retrieved from my database through an AJAX call to another PHP file

I am attempting to dynamically populate my form fields with data retrieved from a database row using ajax. The goal is to send the id of the row I need when a specific button is clicked. Although I have managed to successfully fetch the desired row in the ...

What is the best way to incorporate my light/dark mode theme into index.js and have my header serve as the switch location?

Could someone assist me with setting up a theme around my index.js components and using a switch state in my header.js to toggle between light and dark themes? I'm looking for a way to simplify the process to minimize the amount of code needed. As a ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...

The promise in app.js at line 51471 was caught with an error stating that the navigation from "/customer/login" to "/customer/dashboard" was cancelled due to a new navigation instance

After logging in, I am trying to redirect to another page using router push, but encountering an error. app.js:51471 Uncaught (in promise) Error: Navigation cancelled from "/customer/login" to "/customer/dashboard" with a new navigation ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Element Proxy

I decided to experiment and see how a library interacts with a video element that I pass to it. So, I tried the following code: const videoElement = new Proxy(document.querySelector('video'), { get(target, key) { const name = typeof ...

Babylon entities failing to run

Encountering a strange issue in my current project. I am working on a react application that incorporates Babylonjs for 3D rendering. While I am able to successfully load objects into the scene, I am facing a problem when attempting to create a PBR Materia ...

Bootstrap 5 - centering "padding" both internally and externally within the accordion

Need help aligning three Boostrap 5 grids: Header outside of accordion Overview in accordion header Details in accordion body The accordion header has margins and padding on the left and right, and the collapse icon also occupies some space. I want the ...

The JavaScript feature designed for activating modal popups is only effective for the initial item

I am in the process of developing a clothing shopping website where the main page displays various clothing items. Each garment has an "Add to Cart" button that triggers a popup modal when clicked. However, I am encountering an issue where the modal only ...

How to implement a feature for uploading multiple files through a single form with unique input fields in a web

After searching on Stack Overflow, I couldn't find a suitable solution for my problem. I need help with my code that fetches data and sends it to a PHP file to upload files to specific folders and store their links in a database. However, I am encount ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Two AJAX requests sent with different URLs for success and failure responses

Hello there, I find myself in quite a pickle. I am dealing with an ajax request from select2 and have two different URLs to work with. How should I structure my events to handle success and failure scenarios, where if one URL fails, I can send a request ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

React: When state is updated and a console.log is used, the console displays the previous state instead of the updated

Upon clicking the button, a peculiar sequence unfolds - the console displays 0 and the page refreshes to show 1 function App() { const [count, setCount] = useState(0); const addOne = () => { setCount(count + 1) console.log(count) } ...

Error encountered: "Unable to process Three.js FontLoader due to SyntaxError

I attempted to generate 3D text with FontLoader in Three.js, but encountered an error. My Three.js version is r99. const loader = new THREE.FontLoader(); //https://github.com/mrdoob/three.js/tree/dev/examples/fonts loader.load("./fonts/helvetiker_ ...