Understanding the concept of promises in Angular

Currently, I am working with Angular and CoffeeScript. Within my codebase, there are three functions -

getSomeData1(), getSomeData2(), getSomeData3()
that need to be executed sequentially. The current implementation works perfectly for this requirement.


        getSomeData1: ->
            @http.get("someRestUrl1")
                .success((data) =>
                    getSomeData2()

        getSomeData2: ->
            @http.get("someRestUrl2")
                .success((data) =>
                    getSomeData3()
        
        getSomeData3: ->
            @http.get("someRestUrl3")
    

To enhance readability and improve the understanding of the sequential operations, I aim to consolidate all these functions in one place. Something along the lines of:


        getSomeData1()
        .then(getSomeData2())
        .then(getSomeData3())
    

This proposed structure would significantly aid in clarifying the sequence of actions being performed. Do you have any recommendations on how I can achieve this? Should I consider utilizing $q?

Answer №1

Any ideas on how to accomplish this goal?

To achieve this, simply remove the success calls and directly return the promises from each of those functions using $http. Also, remember to pass callbacks to .then(), not function calls.

fetchData1: ->
    @http.get("apiEndpoint1")
fetchData2: ->
    @http.get("apiEndpoint2")
fetchData3: ->
    @http.get("apiEndpoint3")

fetchData1().then(fetchData2).then(fetchData3)

Is it necessary to use $q here?

No need, as $http already handles that for you by returning promises which can be consumed directly.

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

Can the jQuery Cycle Plugin: scrollHorz with Prev/Next automatically scroll without any input from the user?

Currently implementing the jQuery cycle plugin: jquery.cycle.all.min.js - newest version (2.8.8) available at http://malsup.com/jquery/cycle/ The scrollHorz effect is being used with previous and next links, functioning perfectly except for one issue: upo ...

Is it possible to utilize a JavaScript framework within a Chrome extension?

Currently, I am developing a chrome extension that adds a toolbar to the DOM dynamically. In order to find, attach, and manipulate elements, I have been using CSS selectors in JavaScript. However, this approach has proven to be fragile as any changes made ...

Adding Data to a Database Using Ajax with PHP

I am trying to use Ajax to insert data into a database, but I keep encountering this error: Uncaught ReferenceError: insertData is not defined at HTMLInputElement.onclick (Modal.php:105) Error screenshot: https://i.sstatic.net/AmXka.jpg The HTML and ...

Unallocated functions found within Web Sockets Objects

I am currently utilizing javascript (p5.js) in combination with node.js using express and socket.io. Within my code, I believe the issue lies within this specific section: for (var i = 0; i < 3; i ++){ for (var j = 0; j < 3; j ++){ ...

Explain the concept of declaring a variable and then retrieving a component using an arrow

I'm looking to define a variable within the iteration of a .map() function while also returning a component. However, I've encountered an error when trying to have this variable inside the map. Is this even possible and if so, how would I go abo ...

Tips for avoiding divs from overlapping when the window size is modified

When I maximize the browser, everything aligns perfectly as planned. However, resizing the window causes my divs to overlap. Despite trying several similar posts on this issue without success, I have decided to share my own code. CODE: $(document).read ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

The functionality of cancel and revert in jQuery Sortable is not behaving as anticipated

Issue (Link to problem demo on jsFiddle) I'm encountering difficulties with the revert setting when used alongside the cancel method in jQuery sortable. The cancel method, as outlined in the jQuery Sortable documentation, explains: Cancels a chang ...

Tips on redirecting the user to the page they have selected

<section> <div class="container"> <select name="semester" id="select-semester"> <option value="no-semester">choose a semester</option> <option valu ...

Unraveling the mystery: Retrieving event.target.value in a React component

Having trouble accessing the event.target.value from a React child Component, but not an HTML tag? In this scenario: the Button tag (React Component) cannot access event.target.value, while the button tag (HTML tag) can. import React from "react"; impor ...

Retrieve an element from a child directive within the parent directive

Is there a way to retrieve the element with the class name .second from the second directive in the link function of the first directive? Click here P.S. I have tried it with the template in the link functions, but I specifically need to use templateUrl. ...

A helpful guide on rendering nested maps from JSON data in React.JS

I am attempting to display menu values from a JSON data. This menu has multiple levels, so I am using a nested map function to render the complete menu. const menu = { data:[ { title: "Home", child: [ { title: "SubL ...

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

Guide on building a "like" button using a Node.js Express application

I am in the process of developing a website using node, express, and mongodb. I am facing an issue with passing a variable value from my ejs file to the server side. Can someone help me solve this problem? Here is what I have attempted so far: Example Ht ...

Display data when clicking on Tailwind

I am currently displaying a sub menu on hover using Tailwind CSS. However, I am wondering how I can achieve the exact same functionality by triggering an onclick event instead of hovering over the menu. Here is a DEMO showcasing the current setup. CODE: ...

Unable to Access Camera in Angular5 Instascan: <video> Issue

Having Trouble Displaying Camera View with Angular5 and Instascan, Despite Camera Being On app.component.ts constructor(){ this.Instascan= require('instascan'); let scanner = new this.Instascan.Scanner({ video: document.getElementById("pr ...

Encountering an issue when running the 'cypress open' command in Cypress

I am working with a Testing framework using node, cypress, mocha, mochawesome, and mochawesome-merge. You can check out the project on this github repo. https://i.sstatic.net/ItFpn.png In my package.json file, I have two scripts defined: "scripts": { ...

What are the best ways to get HTML tags functioning properly within Angular.js?

When trying to print a response from a different server that contains a lot of HTML code, how can I display it in a single container? In jQuery, you can achieve this with the following code: $("#xyz").html("<h1>Hello World</h1>& ...

What is the reason for not using ng-attr-width to set the width of this SVG?

I am facing a challenge in understanding ng binding on a simple web page I created to experiment with: <html ng-app="AngularSVGTestApp"> <head> <title>Angular SVG Test</title> <style> svg { backgro ...

Enhance your website's accessibility by using JavaScript to allow the down and up arrow keys to function

Thank you for taking the time to read this, any feedback is greatly appreciated. The current script on my website is only partially functional (click "i" in the bottom right corner). Currently, the script will focus on the first link AFTER pressing the T ...