Comparing Vue JS Promise Execution in Sequential and Parallel fashion

In my VueJS code, I have a working block that needs to be executed sequentially:

  return Promise.all(this.vm.multipleActions.run.map(function (testRun) {
    return self.initiateTest(testRun);
  }))

Currently, it appears that this block runs in parallel. As a result, when I insert records into a database within the initiateTest() function, the ordering becomes random instead of following the order of testRuns, which is what I want to maintain.

I've noticed that the AJAX calls within the initiateTest() function are being made randomly due to the parallel execution.

Answer №1

If you are looking to fetch the outcomes of self.initiateTest(testRun) in a promise similar to how your code handles Promise.all, you can achieve this by using the array reduce function as shown below:

return this.vm.multipleActions.run.reduce((promise, testRun) =>
    promise.then(results => 
        self.initiateTest(testRun).then(result => {
            results.push(result);
            return results;
        })
    ), Promise.resolve([]) // initial promise to chain to
);

Please note: if you are using arrow functions, consider changing self.initiateTest to this.initiateTest. The context of self in your code is not clearly defined.

The resulting promise will resolve with an array containing the resolved outcomes from self.initiateTest(testRun)

For those not using ES2015+, here is an alternative version of the code:

return this.vm.multipleActions.run.reduce(function (promise, testRun) {
    return promise.then(function (results) {
        return self.initiateTest(testRun).then(function (result) {
            results.push(result);
            return results;
        });
    });
}, Promise.resolve([]));

Answer №2

If you want the tests to run one after another in sequence, make sure to call the initiateTest function once the previous test has finished.

var promise = Promise.resolve();
this.vm.multipleActions.run.forEach(function (testRun) {
    promise = promise.then(function() {
        return self.initiateTest(testRun);
    });
})
return promise;

This piece of code initiates a promise that resolves immediately. Each test run is tied to the promise's then handler so they execute only after the preceding promise is resolved.

To make it more concise, you can utilize the reduce method:

return this.vm.multipleActions.run.reduce(function (promise, testRun) {
    return promise.then(function() {
        return self.initiateTest(testRun);
    });
}, Promise.resolve())

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

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

JavaScript library jQuery is unable to locate the element tagged as "<."

I've encountered an issue with setting the value of dropdown options in a web page using strings that contain < and >. Here is an example code snippet: <select id="m" name="m" > <option value="" selected="selected" >All</option& ...

Implementing a Like Feature in Django

Which approach is recommended for integrating like button feature into Django: Option 1: Utilizing solely Jquery and AJAX OR Option 2: Leveraging Django REST Framework in conjunction with a brief AJAX script? ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...

Ensuring that a $(function() is consistently executed and does not diminish over time

Simply put, I am troubleshooting my website and in order for it to function properly, I need to include the following code: <script type="text/javascript"> $ (function() { RESPONSIVEUI.responsiveTabs(); }); </script> What I& ...

When transitioning between forms, I encounter empty values

Currently, I am using JSP and AJAX to extract data from my database and display it in a table. So far, I can retrieve data using any single field without any issues. However, the problem arises when trying to utilize two or more fields simultaneously, resu ...

Tips for incorporating if-else statements into your code

How can I incorporate an if statement into my code to print different statements based on different scenarios? For example, I want a statement for when the sum is less than 1, and another for when the sum is greater than 1. I attempted to use examples from ...

Error encountered while fetching files from Google Cloud bucket using Firebase functions: RangeError - Maximum call stack size exceeded

I'm currently trying to access Firestore backup files stored in a Google Cloud bucket: export const retrieveFirestoreBackup = functions.https.onCall( async (data: RetrieveFirestoreBackupPayload, context) => { try { return await sto ...

Unraveling JSON syntax appears to be an ins

My main challenge is not rotating a DIV, but rather JSON parsing. I need to retrieve the correct attribute value from the variable rotateAttrSet, based on the browser type. I am able to do var rotateAttr = rSET.FF;, however, I am unable to do var rotateAt ...

Is my configuration file causing Express to serve up index.html instead of my Webpack bundle?

My website is having trouble loading because instead of the bundle.js file, it's returning the index.html file. This project was originally created a few years ago and worked without any issues. However, I'm currently trying to revive it and enc ...

Visualizing data from an array within a different Vue component: A step-by-step guide

In my Vue app, I have successfully sent an array from one component to another. However, I am now facing a challenge in visually displaying this data. The issue arises when trying to extract and display specific values, like the date itself. Despite being ...

Testing a subordinate function within the main method that involves HTTP request authorization

Dealing with a tricky situation here, hoping for some guidance. So I'm working with a main method that serves as an api endpoint. This method calls another function to check if the user is authorized to access this endpoint or not. The sub-method, r ...

What is the reason for $http.get not requiring a return value?

I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI f ...

What is the process through which React form elements receive the event parameter?

I'm currently working on a form component that looks like this: import React from 'react'; class CommentBox extends React.Component { constructor(props) { super(props); this.state = { value: '' } this.han ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

I'm wondering if it's possible to fork an npm library in package.json and automatically trigger its build process upon installation

I am currently facing an issue with a npm dependency, such as ngx-infinite-scroll, that I am trying to fork for bug fixes. I want to include my modified version as a dependency in my application. Here is an example of how I have included it in my package.j ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

Guide to implementing AJAX for Google Maps with PhoneGap or Cordova

Recently, I put together a PHP file called maps.php, which includes a basic Google Maps API that seems to function properly on the iPad's built-in browser. However, when attempting to access it via Ajax, the page successfully loads yet fails to displ ...

Select two images and simultaneously move them around on a webpage

Looking for a way to replicate the functionality shown in this image - when I drag one map, another one should automatically move as well. Additionally, the downtown map needs to be contained within the mobile frame. The two map images are located in sep ...

Having trouble with adding data from an array of objects to an HTML element using jQuery's each method

I am currently facing an issue with looping through an array of objects using $.each in jQuery and trying to append the values to an <li>. Here is the relevant jQuery code: $(".sidebar").empty().append("<div>" + "<h5>Student Info</ ...