The process of linking .then functions and triggering a success callback function in Angular.js

I am attempting to chain nested .then functions and execute the success functions, but the callback is being triggered at the beginning.

//public method fn
function fn(callback) {
//calling the 1st API request
fn1()
  .then(function(response) {
    //2nd API request function
    call1(response);
  }, function(error) {
    return $q.reject({
    responseStatus: error.status
  });

  })
  // Returning response
  .then(function(response) {
    callback({
    responseStatus: 200
    });
  }, function(error) {
    callback({
      responseStatus: 500
    });
  });
}

function call1(response) {
  //2nd API
  fn2()
    .then(function(response) {
     //3rd API request function
        call2(response);
      }, function(error) {
        return $q.reject({
        responseStatus: error.status
      });
    });
}


function call2(response) {
  //3rd API request 
  fn3()
    .then(function(response) {
        return lastfunction();
      //here i need to callback the success  response status
      }, function(error) {
        return $q.reject({
        responseStatus: error.status
      });
    });
}


function fn1(){
 //some code 
 }
function fn2(){
//some code 
}
function fn3(){
//some code 
}

//Controller

//i will show response status callback here

if(response.status ==200){
  show output;
 }
 else{
  //response 500
  show errors;
  }

Essentially, I want to send a "200" response status to another controller if all service calls are successful, and if any one request fails, I want to send "500". Currently, with my code, 'response status' 200 is being called within the first .then function. I desire to execute these service calls sequentially in a queue-like fashion.

Any assistance would be greatly appreciated.

Answer №1

Your { responseStatus: x } object serves the specific purpose of managing flow control, a task that can be easily accomplished by the success and error paths of a promise returned by fn();

Furthermore, when utilizing promises, there is no requirement to pass a callback function to fn() - in fact, it is considered poor practice to do so.

To improve your code:

  • Remove all instances of callback
  • Ensure each low-level function returns a promise
  • Simplify the chaining of success events
  • Eliminate unnecessary error handlers
function fn() {
    return fn1().then(call1);
}
function call1() {
    return fn2().then(call2);
}
function call2() {
    return fn3().then(lastfunction);
}
function fn1() {
    //code that returns a promise
}
function fn2() {
    //code that returns a promise
}
function fn3() {
    //code that returns a promise
}

Then, implement the following :

fn().then(function(response) {
    // handle successful response (status "200")
    // display output;
}).catch(function(error) {
    // handle error response (status "500")
    // show error message;
});

The response variable will contain the result delivered by lastfunction(). If you need to aggregate data from fn1(), fn2(), fn3() not already in lastfunction(), refer to this comprehensive solution here.

The error variable will capture the first encountered error during the execution of fn(), providing complete information; access error.message and error.status (if present) for further analysis.

Answer №2

It is important to remember that in order to properly chain promises, you must return the promises you create. When using .then(), keep in mind that you are not modifying an existing promise but constructing a new one in the chain.

Your revised code with returned promises (formatting adjusted):

function fn(callback) {
  return fn1()
    .then(function(response) {
      return call1(response);
    }, function(error) {
      return $q.reject({
        responseStatus: error.status
      });
    })
    // Return response
    .then(function(response) {
      callback({
        responseStatus: 200
      });
    }, function(error) {
      callback({
        responseStatus: 500
      });
    });
}

function call1(response) {
  return fn2()
    .then(function(response) {
      return call2(response);
    }, function(error) {
      return $q.reject({
        responseStatus: error.status
      });
    });
}

function call2(response) {
  return fn3()
    .then(function(response) {
      return lastfunction();
      //here I need to callback the success response status
    }, function(error) {
      return $q.reject({
        responseStatus: error.status
      });
    });
}

function fn1(){
 //some code 
}
function fn2(){
//some code 
}
function fn3(){
//some code 
}

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

What is the best way to access and interpret headers received from my API using angular?

I have a piece of code similar to this on my website domain.com: $http.post("http://api.domain.com/Controller/Method", JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) ...

How to detect changes in Angular 2 using a separate service

Within my AuthService, I store real-time user data and a method for logging in. When the 'Login' button is clicked, the AuthService is called to retrieve updated user data from the server and update the value of 'this.user'. As a resul ...

Angular: Modifying the parent scope from a child component

Hey there! So I'm a beginner in this whole programming thing, but I'm currently working on a small application where I can add and update items with details using Ionic, Cordova, and AngularJS. However, I've hit a roadblock with the followin ...

I have a query regarding the implementation of trackballcontrols.js in three.js

I'm trying to incorporate trackballcontrols.js into my project but I need to make some modifications. I'm having trouble understanding this code snippet, could you provide some explanation? var calculateMousePosition = ( function () { var v ...

Step-by-step guide on saving an array to localStorage using AngularJS

Currently working on constructing a shopping cart. My goal is to include the array invoice in localstorage for future reference. I suspect there may be some flaws with this particular approach. angular.module('myApp', ['ngCookies']); ...

using express to set templateURL in ui-router

I created an Express project with EJS as the views engine. While attempting to set a templateURL for my home views, I keep receiving a 404 error. Below are my code snippets: Code from public/javascripts/angularApp.js: app.config([ '$stateProvider& ...

Can similar named variables be restructured or revised in some way?

const { finalScore1, finalScore2, finalScore3, finalScore4, finalScore5, finalScore6, finalScore7, finalScore8, finalScore9, finalScore10, finalScore11, finalScore12, finalScore13, finalScore14, finalScore15, finalScore16, finalScore17, fin ...

Dynamic binding issue causing audio event to not fire

Currently, I have an <audio> element that is playing audio. When I manually add the event listener onplay in the HTML code, it functions as expected. <audio onplay="alert('t')" .... It's working... However, when I attempt ...

Is it possible for window.open to sometimes fail in opening a popup window?

There is a process that requires an update. In order to update a third-party database, I need to call a service provided by them. My Ajax function is working properly. Below is the code snippet for the success callback. $.ajax({ . . success : funt ...

what is the best way to switch classes between 2 buttons using Angular8

Is there a way to create a toggle button effect that adds an 'active' class to BTN1 when it's clicked, and then removes the 'active' class from BTN1 and add it to BTN2 when BTN2 is clicked? Currently, my code only allows for addin ...

Leverage jQuery for dynamically changing CSS transform properties

Is it possible to update CSS transform values using jQuery with a click event? If not, does anyone have any suggestions on how I could achieve the same effect? I attempted the following code but it did not work for me... $('.reset').on('c ...

An Issue with Selenium IDE Extension Utilizing JavaScript File

As a beginner in Selenium, I am currently exploring the Selenium tool: beginners guide book to learn more about it. The book explains how to utilize the Selenium IDE Extension by using a .js file to store JS functions. An example provided in the book was ...

The functionality of OBJLoader has ceased to function properly following the implementation of revision

Recently, I encountered an issue while working with the objloader feature of the three.js library to display a cube in a web browser. Everything was working perfectly until I updated to revision 55 from git. Since then, I have been unable to render the c ...

What is the best way to retrieve the input value from post.ejs?

app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var passport = require('passport'); var localStrategy = require('passport-local'); var axios = require("axi ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Vue-Router 4 now automatically redirects the default URL to a "404 Page Not Found

I recently decided to upgrade my Vue application from version 2 to version 3, following the official Vue migration documentation. One of the changes I made was updating the vue-router package. However, after updating my router.js file, I noticed that when ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

The file upload functionality is functioning properly when tested with Postman, however, it is encountering issues

I am currently facing an issue with file upload. I am using Angular in the front-end and Java in the backend to upload images to an S3 bucket. The Java code seems fine as I tested the upload URL on Postman and it worked smoothly. Here is a screenshot from ...

Unity Particle Spewer - link up sprays of particles

I'm attempting to create particles similar to the ones in this video: The issue I am encountering is that I am unable to link the particles together. Does anyone have any suggestions on how to achieve this? ...

Avoid using this unauthorized JSONP API - Ways to retrieve information without using the CALLBACK parameter

Dealing with Angular 1.6 Error when Using JSONP despite Receiving a 200 Ok Response from URL I encountered an issue where I need to fetch some data from a JSONP endpoint, and although the response seems to contain the expected data, Angular is still throw ...