Having issues with the forEach and map functions not iterating through every item in an async-await function in Vue.js?

My orders array contains a number of meal plans, each with items inside.

I'm trying to process all orders as paid in the inner loop when I click on place orders. However, the code is only processing some and leaving others behind.

Below is my implementation:

 make_delivery_orders(){
            let self = this;
            var orders = this.deliveryPlans;
            swal('This process will place delivery orders! \nAre you sure you want to continue?' ,{
                icon: 'info',
                buttons: {
                    secondary:"Cancel",
                    danger:"Yes & Continue"
                },
            }).then(async(value) => {
                if(value === 'danger'){
                    orders.map((order,index) => {
                        if(order.included){
                            self.post(siteUrl + '/main/sync' ,   order  ,function(o){
                                if( parseInt(o.result) === 200) {
                                    let r = o.response;
                                    try{
                                        var push = {
                                            data: order,
                                        }
                                        console.log(order)
                                        var url = siteUrl+'/main/print_order_string/';
                                        self.post(url, push,function (res) {
                                            try {
                                                var text = res.response
                                                
                                                // to pay the meal in DB
                                                order.details.data[0].cart.map((item,index)=>{
                                                    app.mealTopay_array.push(item.meal_id);
                                                    setTimeout(function() {
                                                        app.pay_selected_meal(item.meal_id, 1)
                                                    }, 100);
                                                     app.pay_selected_meal(item.meal_id, 1)
                                                    
                                                    console.log(app.mealTopay_array)
                                                })
                                                
                                                // to print the receipt
                                                // app.print_text(text, order)
                                                // app.pay_meal_array()
                                            }catch(e){
                                                console.log(e)
                                            }
                                        });
                                    }catch(e){
                                        console.log(e)
                                    }
                                }
                            });
                        }
                    })
                    self.make_delivery_by_click('sdj')
                }
            });
        },

pay_selected_meal(id, val){
            let self = this;
            console.log(id)
            console.log(val)
            this.post(siteUrl+'/main/updateMealPaid/'+id+'/'+val,'',function (res) {
                try {
                    console.log(res)
                    // insertLog(log)
                }
                catch (e) {
                    console.error(e);
                }
    
                self.loading = false;
            });
        },

Answer №1

Initially, I did not come across any instances of await in the code snippet you provided. Additionally, it's important to note that await cannot be used within JavaScript loop functions like forEach or map. Instead, when using a map, you need to either wait for all promises to resolve or utilize a traditional loop:

for (let index = 0; index < orders.length; index++) 

This is necessary in order to incorporate await inside the loop.

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

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

What is the best way to display a number or integer using axios?

Need help retrieving the integer from the response obtained through an axios get request Here is what I see in the console log: https://i.stack.imgur.com/ztmf0.png setDappList([response.data.stats]); <div>{setDappList.total}</div> Unfortuna ...

Executing an AJAX POST request from one domain (localhost:9393) to another domain (localhost:9696) using Spring Rest

I am encountering an issue with a form on one app running on localhost:9393. The JavaScript function used to post data is: function registerClient() { var postData = $("#client-reg").serializeArray(); var formURL = "http://localhost:9393/mPaws/client/re ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

Is spine.js truly capable of 'streamlining' POST requests?

I recently came across a post by Alex Maccaw, where he discusses the challenges of sending Ajax requests in parallel: Maccaw explains that if a user creates a record and quickly updates it, two Ajax requests are sent simultaneously - a POST and a PUT. How ...

The progress bar for Ng-file-upload does not function properly when used in conjunction with offline

Using ng-file-upload for file uploading in my home has been successful, as I am able to upload files without any issues. However, I encountered a problem where the progress bar only appears when offlinejs is disabled in the index.html file. It seems that ...

Issue with the functionality of socket.io callback functions

Previously, I used to utilize the socket.io emit callback in the following manner: On the client side: mysocket.emit('helloworld', 'helloworld', function(param){ console.log(param); }); On the server side: var server = r ...

WebStorm fails to identify Vue Material Components' HTML tags

When working with VueMaterial in WebStorm, I've encountered an issue where only the <md-list-item> HTML tag is being recognized while others are not listed in the pop-up. This results in unknown HTML tag warnings when using them. https://i.ssta ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Utilizing conditional statements in React js to showcase a distinct component

I am looking to create a function or conditional statement that dynamically displays different components based on whether the user has purchased products. If the user has bought products, I want to display the product components; if not, I would like to s ...

Various titles utilized in Axios patch requests

After spending an hour exploring the Chrome console, I'm still unable to pinpoint the source of this bug. I'm in the final stages of updating the OAuth implementation in my Vue app. It all started when socialLink.js discovered the need to creat ...

Flot seems to be having difficulty uploading JSON files

I am relatively new to working with json and flot, but have been tasked with creating a chart. Can someone please help me troubleshoot why my code is not functioning as expected? $.getJSON('chart.json', function(graphData){ alert(graphData); ...

What steps should I take to resolve the "StrictMode has found deprecated findDOMNode" error?

Whenever I trigger the button to open the drawer, my console displays the warning message '' findDOMNode is deprecated in StrictMode'' The container for the button component is called Sidenav import Sidenav from './Sidenav'; ...

To utilize the span and input text increment functionality, simply use the required input type number and hold either the up or down arrow

Is it possible to increment the value of an input type number by 1 when holding down on a mobile device? <input type="text" id="number" value="1"> <span id="upSpan"> Up </span> $('#upSpan').on('touchstart', function ...

What is the reasoning behind placing CDN links at the bottom of the index file?

What is the reason for placing CDN links for AngularJS file at the end of the index page? I initially placed it at the top of the file and it worked fine. Is there a significant difference between these two placements? ...

What is preventing me from injecting a service into an Angular factory/injector?

I came up with an authentication service (AuthenticationService) that I utilize for making calls to a WEB API. Recently, I stumbled upon interceptors and got intrigued. I thought it would be interesting to create an interceptor that can intercept requests ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

What is the most efficient way to perform an array join in Node.js, akin to the speed of MongoDB's $

Looking to implement a $lookup function in Node.js similar to the $lookup aggregation in MongoDB. I have a solution in mind, but I'm unsure about its performance when dealing with larger arrays or bigger objects. let users = [ {userId: 1, name: ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

There seems to be an issue with accessing /puffins/5f298d0ebcbaf254dcf282b3 at

Having trouble with my destroy route - it keeps returning an error. I've spent a lot of time trying to debug it but no luck yet. Can you lend a hand? All other CRUD routes are functioning correctly. //THE ROUTE app.delete('/puffins/:id', (re ...