What is the best way to ensure all requests have been completed before proceeding?

Is there a way to ensure that the sortOrder function only runs once the getOrders function has fully completed its execution?

I have considered using a callback, but I am unsure of how to implement it. Do you have any suggestions on how I can achieve this?

mounted () {
    this.user = this.$q.localStorage.get.item('userInfo')
    axios.get(`${api.getOrders}${this.user.cpf}`).then(response => {
      this.orders = response.data
      if (this.orders !== '') {
        this.$q.loading.show()
        this.getOrders(callback => {
          this.sortOrder()
        })
      }
    })
  },
  methods: {
    getOrders: function () {
      for (let i = 0; i < this.orders.length; i++) {
        axios.get(api.obterOrderInfo(this.orders[i].orderId)).then(response => {
          this.orderInfo = this.orderInfo.concat(response.data)
        })
      }
    },
    sortOrder: function () {
      this.orderInfo.sort(this.compare)
      this.$q.loading.hide()
    },
    compare: function (x, y) {
      return x.creationDate < y.creationDate
    }
}

Answer №1

fetchOrderDetails: function () {
   // Initialize empty array to store requests
   const requestList = [];
   for (let index = 0; index < this.orders.length; index++) {
      requestList.push(axios.get(api.getOrderDetails(this.orders[index].id)))
   }

   // Resolve all requests and map response data to orderInfo
   return Promise.all(requestList).then(responses => this.orderInfo = responses.map(response => response.data))
},

Answer №2

To effectively handle multiple promises simultaneously, you must group them together and resolve them using Promise.all as illustrated below:

fetchData: function () {
  let promises = []
  for (let i = 0; i < this.dataList.length; i++) {
    const promise = axios.get(api.fetchDataInfo(this.dataList[i].dataId)).then(response => {
      this.processedData = this.processedData.concat(response.output)
    })
    promises.push(promise)
  }
  Promise.all(promises)
    .then(() => {
      this.organizeData()
    })
},

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

Working with JSON data in AngularJS: A guide to loading data onto a scope variable

I am in the process of developing my personal website where I want to be able to update content easily without having to mess with the HTML code. My approach involves loading and updating a JSON file to achieve this, however, I am currently struggling with ...

What is the proper way to utilize mixins from .scss files within .vue files?

Encountered an issue with the error message "no mixin named sm" when attempting to utilize my SCSS mixins in Individual Vue Components, where 'sm' is the name of my mixin variable. The file _mixins.scss is located within the assets/styles folder ...

Working with AngularJS's $q promise and socket.io

I am interested in creating an angularJS promise that can work seamlessly with socket.io. Currently, I have a callback function set up to handle the response like this: function request(event, data, callback) { socket.emit(event, data); socket.on( ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Utilizing multiple materials with a single mesh in three.js: A comprehensive guide

I am facing a major issue with three.js: My goal is to create a simple cube with different colors on each face. I attempted to achieve this using the following code snippet: // set the scene size var WIDTH = jQuery('#showcase').width() - 20 ...

Why is the Rails API throwing ActiveRecord::RecordNotFound error when the User is supposedly present in the database?

I have a Rails 6 API (Backend) running a Vue & Flutter Frontend, Encountering an error when attempting to pass user credentials from Vue to the API: app/controllers/signin_controller.rb:6:in `create' Started POST "/signin" for ::1 at 2019-11-13 02:5 ...

Creating a selectAll checkbox that triggers the ng-click function on each individual checkbox

I've encountered an issue with my code where clicking a checkbox triggers the ng-click function. Here is the JavaScript snippet: $scope.selectTitle = function(evt, selected){ evt.stopPropagation(); var filtered = _.findWhere($scope.se ...

How to use a self-hosted font in a custom Material-UI theme for ReactJS?

Currently, I am in the process of setting up my initial project utilizing Material-UI for ReactJS. My intention is to personalize the default theme by incorporating a custom font (from the server, not sourced from Google Fonts or anything similar). Despite ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

Achieving vertical center alignment in React Native: Tips and techniques

Just a quick heads-up: This question pertains to a school project. I'm currently knee-deep in a full-stack project that utilizes React Native for the front-end. I've hit a bit of a snag when it comes to page layout. Here's the snippet of my ...

"Injecting the value of a jQuery variable into a PHP variable

<script type="text/javascript"> $(document).ready(function(){ $("#t_select").change(function(){ var table_name = $("#t_select").val(); $.ajax({ type: 'POST', ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Automatically hide a label after a certain amount of time following a button click

Currently, I am working with ASP.NET and C#. Within my application, there is a registration form that includes a label to display the status of registration, either success or failure. The content of this label is determined dynamically in the codebehind ...

Could someone assist me in identifying the error or mistake?

For my project, I have implemented client and server sign-in & sign-up functionalities. However, after fetching the register API from the frontend, it is displaying an error message "please fill all fields" even though I have provided validation for al ...

Utilize the power of JavaScript to recursively map object keys

I am working with an array of objects that have varying depths. My goal is to output the names in a specific format: Top Level Top Level > Sub 1 Top Level > Sub 1 > Sub 1-2 Top Level > Sub 2 Unfortunately, I am only able to get the name of th ...

Struggling to update the position of an array and dynamically show its contents using Angular

I am working with an Array of Objects, each containing an Array of strings. Utilizing ng-repeat to display all the strings, I have a button to switch to the next set of strings by changing the selected object in the outermost array. Below is the code snipp ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

Sequence of background colors not altering as intended

After clicking a button, I included the following jQuery code in a code snippet on my WordPress site: jQuery("#cf_course_planner tr").css("background-color", "#f66"); jQuery("#cf_course_planner tr:eq(0)").css(& ...