Is it possible to delay the data until the JavaScript variable has been declared and finished?

I am currently working on the following code. My goal is to ensure that the values are fully processed before executing the dispatch function. However, the issue I am facing is that the dispatch is happening before all the values are retrieved from the foreach loop.

Any suggestions or solutions would be greatly appreciated. Thank you in advance.

executeSyncPO() {
    this.waiting = true;
    this.$store.dispatch('account/checkToken', this.optionValues.syncValue).then((res) => {
        this.waiting = 'stepTwo';
        this.maxCount = res.length;
        
        res.forEach(result => {
            this.POValues.po_number = result.DocNumber;
            this.POValues.vendor_id = result.VendorRef;
            this.POValues.order_date = result.MetaData.CreateTime;
            this.POValues.amount = result.TotalAmt;
            this.POValues.currency = result.CurrencyRef;
            this.POValues.qb_poId = result.Id;
            this.POValues.status = result.POStatus;
            this.POValues.line = result.Line;

            this.$store.dispatch('purchaseOrder/createPO', this.POValues).then(res => {
                this.progress += 1;
            }).then(() => {
                this.$store.dispatch('purchaseOrder/create-lists');
            })
        })
    })

},

Answer №1

Here are a few key points to consider:

Make sure to define the function as async, such as:

async syncPO(){  ...

Instead of using 'wait', make use of 'await' when dispatching actions, like so:

await this.$store.dispatch(
            'account/checkToken', this.optionValues.syncValue
        ).then((res) => {  ...

To ensure the dispatched action returns the awaited promise, declare actions as a var rather than a const:

export var actions = { ...

If you are utilizing axios, remember that your data will be accessed through res.data, not just res.

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

Tips for updating border color when focused with styled-components

How can I change the border color of an input on focus using styled-components and React? Here is the code snippet I am currently using: import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const String ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

Switching Icon in Vuetify Navigation Drawer Mini Variant upon Click Event

UPDATE Here's the solution I discovered: <v-icon> {{ mini ? 'mdi-chevron-right' : 'mdi-chevron-left' }} </v-icon> Is it feasible to modify the icon when toggling between navigation drawer variants? The default varia ...

Adjusting size of a div as you scroll - Java Script

Using the codepen provided at http://codepen.io/anon/pen/fDqdJ, I am looking to enhance the functionality by implementing a feature where, upon reaching a specific distance from the top of the page, an already animated div undergoes a change in scale while ...

Ensuring data integrity within table rows using Angular to validate inputs

I am using a library called angular-tablesort to generate tables on my webpage. Each row in the table is editable, so when editMode is enabled, I display input fields in each column of the row. Some of these input fields are required, and I want to indica ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Struggling to make a function function properly in Node JS using Mongoose

I have been working on adding a search functionality to my application. I managed to create two functions for it, one of which works perfectly fine while the other is causing some trouble. Despite my attempts to troubleshoot the issue, I haven't had m ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...

Tips for refreshing the state in React Native after updating the app

Currently, I am working on developing a login screen with a basic Welcome screen. However, I have encountered an issue regarding the state when refreshing the app - it remains in the splash screen [Indicator] without transitioning to a separate screen. Ide ...

Vue component props are coming back as undefined

I've been struggling for two days to fix this issue on my own, but I just can't seem to get it working. The problem is that even though I declared all my props in the parent component, they're not showing up for some reason. Code Snippet ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Utilizing JavaScript to populate a webview in iOS with data retrieved from Objective C

Can anyone guide me on how to populate an HTML webview with variables stored in Objective-C? I assume I need to use the following code snippet: [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName]; However, ...

Stop the click event using a confirmation dialog before proceeding with the operation

I'm trying to implement a confirmation dialog before deletion by using e.preventDefault() to prevent immediate deletion. However, I am facing an issue in the YES function where I would like to resume the click event's operation with return true w ...

The challenge of parsing nested JSON data with ReactJS and Sockets

My JSON file named "data.json" has the following structure: { "Object1": { "name": "1", "rank": "2" }, "Object2": { "name": "3", "rank": "4" } } In my React code, I am setting the state using this data. I w ...

What is the process for verifying an email address using the deep-email-validator package from npm?

I'm looking to verify the existence of an email address used for registration on my website, ensuring it's not just a temporary one. How can I achieve this utilizing the npm deep-email-validator package? Within my HTML page, I've assigned n ...

Troubleshooting the Cross-Origin Resource Sharing Problem in Angular and

I had my client hosted on localhost:8080/ and the server on localhost:44302/ I am attempting to connect to my backend, but I keep encountering CORS issues. Here is my Angular http request: $http.post(url, data, { headers: { ' ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Importing text data from a text file in Java or jQuery without the need for a web server

I've attempted to utilize both the jQuery.Get() and $.Get() methods for this task, but they don't seem to be working as expected. <head> <script type="text/javascript" src="jquery-2.1.3.min.js" > </script> <script lang ...

Avoid an issue where the v-btn (floating action button) placed at the top in an absolute position does not extend beyond the boundaries of the v-card in

I'm struggling with keeping this visible when it exceeds the component's boundaries. Any tips on how I can achieve that? Thanks in advance for your assistance. <v-card> <v-btn @click="dialog = false" fab small absolute top right c ...