Combining several promises in AngularJS

Looking to simplify the structure below:

Reusable service1 for IndexedDB interactions


function isDbExist (){
// do something , returning either reject or resolve
}

function createDB (){
// do something , returning either reject or resolve
}

function getData (){
    // do something , returning either reject or resolve
}

In another service2, I'm injecting service1 and using the functions like this:


function1 (){
service1.isDbExist.then(function(data){
   service1.createDB.then(function(data){
      service1.getData.then(function(data){
        referred.resolve(data);
      },function(error){
       deferred.reject(error)
      })
   },function(error){
    deferred.reject(error);
   })
},function(error){
   deferred.reject(error);
})
}

The issue here is that the code is not very readable, making it difficult to debug which reject function corresponds to which promise. Is there a better way to handle this? I have looked into $q.all but don't think it's applicable in this scenario.

Answer №1

One great thing about promises is the ability to chain them together instead of nesting callbacks. You can easily return another promise within a promise like this:

checkIfFileExists().then(function(file) {
  // do something
  return createFile();
}).then(function(file) {
  // perform actions with the resolved file
  return getFileData();
}).then(function(data) {
  // Handle data accordingly
}).catch(function(error) {
  // Oops, an error occurred. Handle it gracefully
});

Lastly, you can handle any errors that may have arisen during the process.

Answer №2

To link together multiple promises, follow this pattern:

task1.checkExists()
    .then(task1.startTask)
    .then(task1.completeTask)
    .then(function() {
        // Task checked, started, and completed
    })
    .catch(function(err) {
        console.log('Error handling', err); // checkExists, startTask, or completeTask was rejected
    });

Take a look at the live demonstration to understand how success and error information is transferred to the next promise in the sequence, and how you can oversee each step of the process:

Live Demo: http://plnkr.co/edit/PM06e8NGJvHKmoJ9C2Lf?p=info

Answer №3

One amazing aspect of promises is their ability to be linked together in a chain, as shown here:

performAction (){
  return service.checkAvailability.then(function(available){
    if(!available) return service.initialize()
  })
  .then(function() {
    return service.fetchData('some', 'parameters')
  });
}

It's important to note that the .then method will receive the output of the previous function, such as the availability being a boolean value. The `performAction` function will also return a promise, which will resolve with the result of the service.fetchData promise.

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

Writing the success function for a jQuery ajax call involves defining the actions to be taken once

Embarking on my journey to learn jQuery and web development, I am faced with the task of sending user input (username and password through a submit button) to a PHP page using .ajax and success function. Below is the HTML form code: <form id="form1"&g ...

Error parsing PHP string arrays into JavaScript string arrays

My attempts to convert a name string array from PHP to Javascript have been unsuccessful. var name = <?php echo json_encode($eventname); ?>; and var name = new Array("<?php echo implode('","', $eventName);?>"); I expected the ou ...

retrieving the smallest and largest values from a date range selector

I have been implementing a date range slider following the guidelines from this resource. I successfully set up the slider according to the documentation, but now I need to retrieve the minimum and maximum values as the slider is being moved. I attempted t ...

Display a span element using jQuery datatable to indicate that the update operation was

I have implemented inline editing using jQuery Datatables. Currently, I am trying to display a green checkmark when a record gets updated. Below is the ajax call that populates the table: $.ajax({ url: 'api/massEditorSummary.php', type: &ap ...

Ways to display the data within a BLOB object

On this page, the user is showcasing a table with three columns - tipo_esame (string), data_esame (string), and uri (BLOB). const archiveItems = this.state.archive.map((archive, i) => { return ( <tr key={archive.hash_referral}> <td ...

Dealing with extended render times in React applications

Currently, I'm working with a limited set of 100 documents per page and utilizing a wrapper component for certain conditional actions. const onClickCheckbox = (order: OrderProps) => { const _ordersToExport = [...ordersToExport]; const ind ...

The jquery click event is not working as expected

Hey there, I've been working on creating a dropdown menu that can be activated by clicking for better usability on touch screens. $('a.dropsmall2').click(function() { $(this).next('ul').slideToggle(500,'easeInOutQuad'); ...

Accessing properties like $vuetify using getCurrentInstance() in Vue 2.7

Currently, I am in the process of upgrading from vuetify 2.6 to 2.7 for the composition-api functionality. However, I am encountering numerous errors when attempting to access properties of the Vue instance. For example, I am using Vue with Vuetify and hav ...

Creating a two-dimensional perspective in Three.js

I am new to utilizing three.js and I am currently attempting to create a 2D visualization using these 3D tools for layered sprites. I am looking for guidance on the arguments for PerspectiveCamera() and camera.position.set(). I have received some helpful h ...

Updating multiple nodes in a Firebase database can be achieved by utilizing the `then`

When dealing with denormalized data in Firebase, updating multiple nodes can become cumbersome. Each update operation must wait for the previous one to succeed. The current approach shown below is not very readable and can get even more confusing as more ...

Testing a custom Angular directive that encapsulates the functionality of SlickGrid

Currently, I am working on testing an angular directive that acts as a wrapper for slickgrid. 'use strict'; describe('Unit: Grid Directive', function() { var $scope; var element; beforeEach(module('grid')); beforeEac ...

Post Data with Nested Objects Using Axios

I am facing an issue where I want to store multiple options in an array named options from a form that contains textboxes. However, instead of each option being added under the parameter options, they are getting overridden by one another. hooks const [ ...

Error Type: Unable to access the X property because it is undefined

I have this Interface that serves as a type for a JSON file: export interface IIndustrySectors { IndustrySector: string; isSelected: string; dataSubjectCategories:string[]; dataTypeCategories:string[]; SubIndustries:[{ IndustrySector: stri ...

What is the process for incorporating an external script into a Vue component?

Seeking assistance urgently... I am encountering an issue with a Vue component and an endpoint that provides a script containing a small menu with actions. However, once the script is loaded, the actions do not seem to function on the page and I cannot det ...

Find the total sum of numbers associated with strings that are repeated in two separate arrays

Consider the following scenario where I have 2 arrays: categories = ["hotels", "transfers","food","transfers"] amounts = [1500, 250, 165, 150] The goal is to create an object that will look like this: result = {hotels: 1500, transfers: 400, food: 165} ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Evaluating time stamps consistently

I am attempting to pass an unlockTime prop to a component1 in order for it to be rendered after the specified time has elapsed. How can I make Vue continuously check if the current time is greater than the unlockTime (Date.now() > this.unlockTime ? tru ...

The YYYY-dd-mm input mask pattern is malfunctioning

Hello, I am having trouble creating a pattern for an input field in the format YYYY-mm-dd. My code is not working properly. Can someone please help me correct my code? Any assistance would be greatly appreciated. <html> <head> <title>En ...

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...