What is preventing the function from waiting for the promise to be resolved?

I am encountering an issue with the code snippet below. The control does not wait for the HTTP promise to be resolved before returning a string from the method, and I can see that the returned object is "method" in the switch statement. Can someone please help me figure out what mistake I have made here?

The controller contains the following logic:


var status = function(action) {
    switch(action) {
        case 'create':
            return $scope.submitdata();
            break;
        default: alert();
    }
}

$scope.submitdata = function() {
    service.postdata($scope.formdata)
        .success(function(data) {
            $scope.response = data;
            return 'SUCCESS';
        })
        .error(function(error) {
            Console.log(error);
            return 'FAILURE';
        })
}

Service Method:


this.postdata = function(data) {
    return $http.post(URL, DATA);
}

Answer №1

When using the .success and .error methods, remember that they do not consider return values.

It's important to note that parameter values are sensitive to case.

this.postData=function(data){
    //THIS
    return $http.post(URL,data);
    //return $http.post(URL,DATA);
}

Notification of Obsolescence1

The use of the legacy promise methods $http, such as .success and .error, has been deemed obsolete. Instead, opt for the standard method .then.


$scope.submitDataPromise = function() {
    return service.postData($scope.formData);
});

$scope.submitDataPromise
  .then(function onSuccess(response){
    $scope.data = response.data;
    //return data for chaining
    return data;
}).catch(function onError(response){
    console.log(response.status);
    //throw for error chaining
    throw response;
});

Upon execution, the submitDataPromise function promptly delivers a promise. This promise serves as a vessel for forthcoming results of the XHR resolution, whether fulfilled or rejected. These outcomes can be accessed by assigning functions through the $q service to be executed upon resolution.

The response object encapsulates these attributes:

  • data – {string|Object} – The response body transformed via transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header retrieval function.
  • config – {Object} – The initiation configuration object for the request.
  • statusText – {string} – HTTP response status text.

An HTTP response status within the range of 200 to 299 denotes success and triggers the invocation of the success callback. If the response entails a redirect, XMLHttpRequest will automatically follow it, preventing the error callback from being triggered in such scenarios.

-- AngularJS $http Service API Reference - General Usage

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

Upon triggering an ajax post request, the HTML elements do not refresh as expected within an Angular environment

I am facing an issue where I make an AJAX POST request and it executes properly. After receiving the response, I need to make another AJAX GET request and assign the data to variables in the scope. The data is successfully assigned to the variables, but th ...

Leveraging a query to fetch the most recent value and update it in Firebase using AngularJS 1

After setting up my database with the following entries: service/ -KSxobYDhjUJeSvu3dC1 -Accion:"Nueva ronda" -Codigo: 3 -dateTime: 1475284727 -notify: 0 -num_mesa: 0 -KSxobptdYSc-qrCSbyU -Accion: "Orden cancelada" -dateTime: 1475284728 -notify: 0 ...

NuxtLink sending users to incorrect destination URL

I am facing an issue with my static generated Nuxt site. Everything works perfectly fine when I host it locally, but once I load it on GitHub Pages, the NuxtLink elements' hrefs are incorrect. For instance, one of my links looks like this: <NuxtLi ...

Fancybox may be difficult to spot when using Safari

Currently, I am utilizing fancybox with the latest versions of jquery.min.js (3.3.1), jquery.fancybox.css (3.5.7), and jquery.fancybox.pack.js (3.5.7). Everything is functioning as expected on all browsers except for Safari. On Safari, the content within ...

Adjusting Picture Sizes to Fit the Dimensions of a Photo Frame

Currently, I am in the process of developing a website that incorporates two distinct image types: Portrait photos Landscape photos As you can see, there are two different categories of images: Square Rectangular I need to resize all the phot ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

Creating a unique array of non-repeating numbers in ES6:

Looking to create an array of unique random numbers in ES6 without any repeats. Currently, my function is generating an array of random numbers that are repeating: winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53)); Here is a non-ES6 ...

Is it possible to assign a class to the initial word within a designated class?

How can I customize the first and second word of a specific class in my code? This is an example of my current code: <h2 class="content-heading">Latest News</h2> I would like to achieve something similar to this: <h2 class="content-headi ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. https://i.sstatic.net/RMKU9.png ...

Using JQUERY to execute a callback function after an AJAX request is completed

I encountered a situation where I have the following code snippet: <a onclick="$('.element').hide(0); doMyMethod(_element = $(this));"></a> The doMyMethod() function is actually an ajax request. What I am trying to accomplish is to ...

Having trouble with table sorting in Jquery?

I am a beginner in the realm of Jquery and web programming. Recently, I attempted to implement the tablesorter jquery plugin for one of my projects but encountered issues with making it work properly. In search of a solution, I turned to Stack Overflow. C ...

Steps for displaying innerHTML values conditionally with a pipe

Currently working with Angular 8 and looking to conditionally implement the innerHTML feature using a translation pipe. .html <button type="button" mat-flat-button // utilizing translate module internally [innerHTML] = "display ? (HIDE ...

Issue encountered when updating npm to version 5.4.2: Unable to locate modules in ./node_modules/react-router-dom

When attempting to update my npm version from 3.10.10 to 5.4.2 and migrate react from 15.3.0 to 16.0, I deleted the node_modules folder and re-ran npm install. However, upon trying to run my application again, I encountered the following error: ERROR in ./ ...

How to upload a document to Alfresco using JavaScript API

I am facing an issue while attempting to upload a file from a node application to my local Alfresco server. I have been able to login, create, and delete folders successfully, but I am encountering difficulties when trying to upload files. let AlfrescoApi ...

Choose a collection of elements and encase them within a <div> tag

I am currently working on creating a greasemonkey script for a webpage that has a rather challenging structure. My goal is to show and hide different entries, but the content is formatted like this: <a name="first"/> <h3>First</h3> Some ...

Looping through an array

I have created an array as shown below: iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true] Condition check: If any value in this array is false, I will display an error messag ...

Is it possible to transfer the reactivity of a Vue ref to another ref while reassigning it?

Below is a simplified version of my Vue component: <template> <div @click="loadEvents">{{ loading }}</div> </template> <script setup> import { ref } from 'vue' let loading = ref(false) loadEvents() func ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

How can I convert text containing in Node.js and insert actual new lines instead of the character?

I'm trying to transform a text response by removing special characters like \n and turning them into actual new lines. The initial response contains special characters -----BEGIN MESSAGE----- v1.60 hQEMAwPgeMJUXSL5Bps+U3lC8tnc D8s2Aeb7UtryIRAB ...