Waiting for a response is not the same as waiting for firebase batches functions

There's a simple function that sets the loader value to true and then, when the function finishes, it sets it back to false. However, I'm facing an issue where my async/await functions are not properly awaiting the code that involves firebase batch writes. Here's a snippet of my code:

const updateNegotiation = async title => {
  negotiationLoader.value = true
  await store.dispatch('actionUpdateNegotiation', {
  negotiation: listFromDialog.value, 
  title: title, 
  loader: negotiationLoader.value
  })
  negotiationLoader.value = false // the loader's value should be set to false after await
}

Additionally, here is the firebase function that uses batch writes:

//vuex

async actionUpdateNegotiation({commit}, deal){
        const batch = db.batch()
        const reference = db.collection('negotiations')
        .doc(moduleUser.state.user.email)
        .collection('deals')

        const setRef = reference.doc(deal.title)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.set(setRef, deal.negotiation)
        batch.update(setRef, {
          ...deal.negotiation,
          status: deal.title
        })
        const deleteRef = reference.doc(deal.negotiation.status)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.delete(deleteRef)
        
         try{
          batch.commit()
          return {
            res: false
          }
        } catch (error) {
          console.log(error);
          return{
              error,
              res: true
          }
        }
      }

Answer №1

The keyword await only serves a purpose when the code being called returns a promise. Simply marking actionUpdateNegotiation as async is not sufficient in this case.

It appears that the only asynchronous operation within actionUpdateNegotiation is the call to batch.commit(), so you can make the function return a promise by including:

return batch.commit()

Alternatively, you can also utilize await:

await batch.commit()

Answer №2

Make sure to enclose your actionUpdateNegotiation within a promise.

async actionUpdateNegotiation({commit}, deal){
        return new Promise(function (resolve, reject) {
            const batch = db.batch()
        const reference = db.collection('negotiations')
        .doc(moduleUser.state.user.email)
        .collection('deals')

        const setRef = reference.doc(deal.title)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.set(setRef, deal.negotiation)
        batch.update(setRef, {
          ...deal.negotiation,
          status: deal.title
        })
        const deleteRef = reference.doc(deal.negotiation.status)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.delete(deleteRef)
        
         try{
          batch.commit()
          resolve(false);
        } catch (error) {
          console.log(error);
          reject({
              error,
              res: true
          });
        }
        });
      }

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

Leveraging environment variables within a React app

Just when I thought I had a handle on things, our JavaScript resource decided to quit. Now, as someone with zero knowledge of front-end development, I find myself in charge of getting the UI up and running. My current hurdle involves using an environment v ...

The auto-play feature fails to function on iPhone devices when using Reactjs

I am currently working with Reactjs and Nextjs. I have a video on my website that is functioning properly on Android phones but not on iPhones. How can I resolve this issue? I have attempted the following code: <video loop autoplay='' muted> ...

The JQuery onchange event functions as expected multiple times within JSFiddle, but seems to only fire once in the

A jQuery (1.11.1) script has been implemented on a business catalyst site cart page to show or hide a message based on the dropdown option selected by the user. The script functions correctly multiple times in jsfiddle at http://jsfiddle.net/NathanHill/462 ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

Acquiring user information from Firebase using Angular 2

Here's a signup code snippet that pertains to my previous inquiry on Stack Overflow about adding user data upon account creation. The code is as follows: signup(){ firebase.auth().createUserWithEmailAndPassword(useremail, userpassword) .then(fu ...

Sharing an array with a child component using the @Input decorator

I am attempting to send an array to a child component. The array is created within the subscribe method of the onInit lifecycle hook in the parent component. Parent component: import { Component, OnInit } from '@angular/core'; @Component({ s ...

Displaying asynchronous data in a VueJS template

This is the current code snippet I am working with: <template> <div> <hot-table licenseKey='non-commercial-and-evaluation' :data="covertDataToTableReadable" colHeaders="true" width="600" height=& ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Adding various values from an interactive form

My database has two rows titled start_time and end_time. I am trying to insert values from a dynamic form using implode() but facing difficulty in inserting values from the subsequent input fields. https://i.sstatic.net/khTu6.png Database https://i.ssta ...

Is three too much for the Javascript switch statement to handle?

I'm a beginner in Javascript and am working on a project to create a fun program involving astrological signs, planets, and houses to generate a story. I have included three switch statements within one function to accomplish this. I'm encounter ...

Lack of data in the request body of a Node.js

I'm a beginner with node.js and I've run into an issue trying to send data from the client to the server. Below is the code on the client side: var roomName = document.indexform.room[1].value; const roomInfo = { value: `${roomName}`, text: `${roo ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

Using @keyup/@input events on Vue data property causes issues with form inputs

I'm having an issue with attaching a character counter to an input element. After displaying it back to the user, the input stops allowing me to enter more characters into the input box. <template> <div> <label class="l ...

What could be the reason behind the validation failure of this Javascript code?

After implementing your recommendation, this is my current status: <script> function tick() { const React.element = ( '<div><marquee behavior="scroll" bgcolor="lightyellow" loop="-1" width="100%"> <i> <font color ...

I am a beginner in node.js and currently exploring the concept of asynchronous callbacks and how they function

When running the following code, "one" and "two" are displayed as output but "three" is absent. Can someone provide an explanation as to why "three" is not showing up in the output? Despite trying various methods, I am still unable to pinpoint the cause ...

Obtaining the value of an HTML span tag during execution on a PHP Webdriver client and Selenium can be achieved

Currently working with the php webdriver client along with selnium Struggling to retrieve the value from the span tag showing Rs 350 <div class="fareBlock busDataBlock"> <div> <span class="fareStart">< ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

Guide to utilizing both an HTTP server and a socket connection simultaneously

Currently, I am using an http server with a socket connection for handling responses to http requests. I have been storing the response object res in a global variable, but I believe this may not be the correct approach. Can someone suggest the proper me ...