One can pass parameters to a promise's success callback within AngularJS using $q

I have encountered a situation that is similar to the one described in this post, but I am still unsure about how to implement it. I could use some assistance with setting up a successful callback.

This is the current functioning code:

function getStuff(accountNumber) {
    var logMessage = 'POST GetStuff';

    return $http.post(GetStuff, { custId: accountNumber })
        .then(log);
}

function log(response) {
    logger.debug(response);
    return response;
}

This is my desired goal:

function getStuff(accountNumber) {
    var logMessage = 'POST GetStuff';

    return $http.post(GetStuff, { custId: accountNumber })
        .then(log(response, logMessage));
}

function log(response, logMessage) {
    logger.debug(logMessage, response);
    return response;
}

Answer №1

Here is a helpful function:

function retrieveData(accountNum) {
    var logMsg = 'POST RetrieveData';

    return $http.post(RetrieveData, { customerId: accountNum })
        .then(
           function handleSuccess(res) {
               return log(res, logMsg);
           }
        );
}

Answer №2

For those with specific preferences or requirements, there are a couple of options to consider. Personally, I usually write promise callbacks in the following manner:

.then(function success(response){
  return log(response, logMessage);
});

Alternatively, some may not favor this approach (I understand that it's not universally liked and should only be used when absolutely necessary):

.then(log.bind(null, response, logMessage));

Would either of these methods suit your needs?

Answer №3

Take a look and see how this code snippet can be useful:

function fetchItems(user_id) {
  var logMessage = 'GET FetchItems';
  var deferred = $q.defer();

  return $http.get(FetchItems, { userId: user_id })
   .then(function(response){
      deferred.resolve(response);
      log(response, logMessage);
   }).catch(function(){
      deferred.reject();
   })     
   return deferred.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

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

What are some ways I can efficiently download large attachments without disrupting the user's experience?

I'm encountering some challenges with handling large attachments in my project. Initially, I had this link code: <a :download="scope.row.name" :href="`data:${scope.row.type};base64,${scope.row.contentBytes}`">download</a& ...

Fetching JSON data using Javascript/JQuery

My goal is to access JSON data from an online web service that queries a MySQL database for a specific string and use Javascript to present it on an HTML page. My challenge lies in effectively displaying the retrieved information. The relevant part of my ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

Inserting a value into a Node/Express session

I am currently immersed in a project that involves Node, Express, and MongoDB. Mongoose is the tool I use to shape my schemas and interact with the database. In addition, I utilize the "express-sessions" module where a session value named "req.session.user ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

"Every time ajax is called, it will always generate

function lks() { var groupname = document.getElementById('groupname').value; $.ajax ({ url: 'verifyGroup.php?groupname='+groupname, type: 'get', ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Ways to dynamically assign a name to a div using AngularJS

Currently, I am in the process of developing a download function for an Android app using Angularjs based on this tutorial: Utilizing the Progress event in PhoneGap file transfers Everything seems to be working efficiently as planned; I can successfully d ...

The image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

"Creating a Hyperlink that Navigates to Specific Content Within a

I have a situation where I am trying to link to sections on the page contained within collapsed fieldsets. My goal is that when a user clicks on this link, the page should scroll down and automatically expand the fieldset to display the content inside. E ...

Learn how to access an array within an object using JavaScript and an API URL

Trying to fetch data from the swapi API to display film titles using jQuery. Below is the JavaScript code: $(function(){ function promiseTest(){ return $.ajax({ type: 'GET', url: 'https://swapi.co/api/people/', } ...

Challenges with Vuex and updating arrays using axios

I am currently facing a challenge with VueJS Vuex and Axios: The issue arises when I retrieve an array with Axios and loop through it to populate its children this way: "Rubriques" has many self-relations, so one rubrique can have multiple child rubriques ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...