Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular.

The code snippet I've written looks like this:

$q.all({
  a: $q.then(func1, failHandler),
  b: $q.then(func2, failHandler),
  c: $q.then(func3, failHandler),
}).then(func4);

Is it guaranteed that the execution will always be func1, func2, func3, func4?

Because I am experiencing func4 being triggered before the other three functions. This raises another question.

Does $q.then(callbacks).then always ensure that the callbacks are executed before moving on to the next then?

Answer №1

Important Note:

The examples provided below are purely for demonstration purposes and should not be used in a real application. Some of them may even fall under The Deferred anti-pattern. They are meant to showcase how certain functions work.

To address the question at hand, let's conduct some experiments to explore it further.

Given the following callback functions:

function okHandler(value) {
  console.log(value + ' has been called.');
  return value;
}

function doneHandler(values) {
  console.log('Done! : ' + JSON.stringify(values));
}

function delayed(value, delay) {
  var deferred = $q.defer();

  $timeout(function () {
    deferred.resolve(value);
  }, delay);

  return deferred.promise;
}

Parallel Execution:

$q.all({
  a: $q.when('a').then(okHandler),
  b: $q.when('b').then(okHandler),
  c: $q.when('c').then(okHandler),
}).then(doneHandler);

Result:

a has been called.
b has been called.
c has been called.
Done! : {"a":"a","b":"b","c":"c"} 

Parallel Execution with Delay Simulation:

$q.all({
  a: delayed('da', 200).then(okHandler),
  b: delayed('db', 100).then(okHandler),
  c: delayed('dc', 300).then(okHandler),
}).then(doneHandler);

Result:

db has been called.
da has been called.
dc has been called.
Done! : {"b":"db","a":"da","c":"dc"} 

Sequential Execution:

delayed('sa', 400).then(okHandler).then(function () {
  delayed('sb', 100).then(okHandler).then(function () {
    delayed('sc', 10).then(okHandler).then(doneHandler);
  })
});

Result:

sa has been called.
sb has been called.
sc has been called.
Done! : "sc" 

Alternative Sequential Style:

delayed('ssa', 600)
  .then(okHandler)
  .then(delayed.bind(null, 'ssb', 100))
  .then(okHandler)
  .then(delayed.bind(null, 'ssc', 10))
  .then(okHandler)
  .then(doneHandler);

Result:

ssa has been called.
ssb has been called.
ssc has been called.
Done! : "ssc"

Example Plunker: http://plnkr.co/edit/dNZ8koAS4G6fNmahfmj6?p=preview

Now, let's proceed to address your specific queries.

Q: Is the execution order always guaranteed to be func1, func2, func3, func4?

A: No, only func4 is guaranteed to be executed last. The sequence of func1, func2, and func3 can vary.

Q: Does $q.then(callbacks).then always ensure that callbacks are fired before moving to the next then block?

A: Yes!

Answer №2

It's important to differentiate between promises and Q.

Promises are a powerful abstraction that includes a then method.

Consider using $q.defer() and remember to resolve it when needed.

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

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

The program failed to run properly because it couldn't find the reference to Chart

I added chart.js to my project using npm with the command: npm install chart.js --save-dev. In the file "resources/assets/js/bootstrap.js", I included it by using: require('chart.js');. After running npm run dev in the console, it compiled succe ...

The static files are being received by Django but are not functioning properly

I've been working on a project using django 1.7, and below is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = "absolute/path/to/static" In the 'assets&apo ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

Are there any plugins available that can create a Ken Burns effect using JQuery?

All I need is a straightforward plugin, not one for creating slideshows. In this case, I only have 1 div and 1 image. The goal is to have the image animate within the div, shifting left/right or up/down without any white space visible. The size of the ima ...

Reveal the concealed button with a jQuery click event

I have a simple question that has been elusive to find an answer for on the internet. Can anyone please help? <input hidden="true" class="btnsubmit" id="myaddslide2" onClick="UPCURSLIDE()" type="button" value="UPDATE"> <script> function ...

What are the steps for encoding a value using jquery serialize?

I attempted to encode all values using the following code: encodeURIComponent($("#customer_details").serialize()); Unfortunately, it did not produce the desired results. Is there a method to retrieve all elements on a form and individually encode each v ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

The most effective method for modifying a prop in VueJS without altering the parent's data

In the main Vue component, there is an object named user. If I pass this user object as a prop to a child component: <child :user="user"></child> When updating user.name in the child component, the changes also reflect in the parent componen ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Showcasing the values of JavaScript

How can I resolve the issue depicted in the second picture? I need the value of 3 only in the USD column, with all others having a value of zero. <div class="span3"> <ul class="nav nav-tabs nav-stacked" > <?php foreach ( ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

How to handle data resolution in AngularJS $q.all within a service instead of a controller

I have recently updated my code so that all model creation now happens within my factory rather than the controller. While this approach is effective, I am facing an issue where the promises are not being resolved in order during initialization. When att ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

How to Retrieve Post Data for Each Field in AngularJS

Utilizing ng-model, I can easily retrieve data from a post by assigning an ng-model value to each field and accessing it from the $scope. But what about retrieving all fields values from a post without knowing each individual field? I'm looking for ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...