Is Restangular taking forever to resolve the promise?

Just starting out with JavaScript and AngularJS, and this particular issue has me stumped.

Requirements

  • A RESTful service that retrieves data from the backend
  • AngularJS 1.2.21 and Restangular 1.4.0 being used
  • An AngularJS controller tasked with requesting an enhanced version of the provided data from the service

Current Setup

The method causing confusion is as follows:

   service.getSlices = function() {

        Restangular.all('entries').getList().then(function(entries) {

            // complex modifications to the data take place here
            // ...

            return resultOfModification; // intended returned value for getSlices();
        })

        // need to ensure resultOfModification is returned here

    };

The Dilemma

Essentially, I want `getSlices()` to wait until the promise is resolved before returning `resultOfModification` once it's computed.

Another Approach
I have considered returning a promise from `getSlices()` which would deliver `resultOfModification`. However, my understanding may not be sufficient enough at the moment due to frustration or exhaustion.

Any answers or suggestions are greatly appreciated, especially recommendations on helpful resources. Thank you!

Answer №1

It's not possible to return the actual value in that place because Restangular operates asynchronously (the function getSlices moves on before the callback you provide to then is executed). That's why it's recommended to utilize Promise.

Even if synchronous behavior could be forced upon Restangular, it's advised against due to the negative impact it would have on user experience by blocking the browser until the data is fetched.

It's important to familiarize yourself with Promise as they were developed to resemble synchronous code while functioning asynchronously.

To make a necessary change in your code, add a return before Restangular.all:

  service.getSlices = function() {
      return Restangular.all('entries').getList().then(function(entries) {

          // complex modifications to backend data go here
          //...

          return resultOfModification; //this should be the returned value for getSlices();
      })
  };

This will return the Promise from the .then call. The Promise resolves to

resultOfModification</code which is what is returned from its callback.</p>

<p>You can then use <code>getSlices
like this:

  service.getSlices().then(function(modifiedData) {

  });

Promises can be chained together:

  (new Promise(function( resolve, reject){
    setTimeout(function() {
      resolve("some");
    },200);
  }))
  .then(function(data) {
    return data+' data';
  })
  .then(function(data) {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(data+' !!!!!!');
      },200);
    });
  })
  .then(function(data) {
    console.log(data);
  });

This is equivalent to:

  var promiseA = new Promise(function( resolve, reject){
    setTimeout(function() {
      resolve("some");
    },200);
  });

  var promiseB = promiseA.then(function(data) {
    return data+' data';
  })


  var promiseC = promiseB.then(function(data) {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(data+' !!!!!!');
      },200);
    });
  });

  var promiseD = promiseC.then(function(data) {
    console.log(data);
  });

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

Leveraging Bootstrap grid system within AngularJS elements

I am currently working on wrapping grid element divs into Angular components in order to streamline the input process and establish a standard: <bootstrap-row> <bootstrap-input-text col=6 ng-model="$ctrl.model" label="hey!"& ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Repetitively showcasing data in asp.net mvc

Here is my LINQ code snippet: public JsonResult getfull() { var coursename = Session["course"].ToString(); var location = Session["location"].ToString(); var result = (from insti in db.Institute_Master ...

Implement an onClick event to the newly created th element using document.createElement()

Through the use of document.createElement("th"), I am dynamically inserting columns into a table. var newTH = document.createElement('th'); Is there a way to add an onClick attribute to this element so that users can delete a column by clicking ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Exploring Angular testing by using mock services to simulate the behavior of other services

I am familiar with how to mock a function call to a service. However, I am facing a scenario where my MainService acts as a wrapper for multiple other services. export class MainService { constructor( public service1: Service1, public service2 ...

How to Validate Response/ Data value from PHP using Ajax

Currently, I am in the process of validating a sign-up form by utilizing ajax to call a php script that checks for existing email addresses. If the email address already exists in the database, an error message should be returned to the ajax function throu ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

Instructions for activating a button in the absence of any inputs

I need help enabling a button in angularjs based on whether any of the inputs are filled out. I was successful in disabling a button when only one input is checked, but how can I do this for all inputs affecting one button? This is what I've attempted ...

Attempted to fetch information using Ajax in Grails

I am attempting to utilize jQuery and ajax with the Grails framework to load the content registration page. However, upon loading the page, I am encountering an issue where the menu and registration fields are duplicated within the page. <script src ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Hmm, I seem to be encountering an error where res.sendStatus is not recognized as a function. What could be causing this

For the last few months, I have been immersed in Node.js/Express to create a REST Api. However, I've hit a roadblock with an async function in my controller.js file. The callback function is successfully receiving the client's request, but when i ...

Tips for maintaining server session by tracking user activity on the browser using a simple ajax request to the server without relying on JQuery

In my website, the server session Timeout is set to 30 minutes. <system.web> <sessionState timeout="30" /> </system.web> However, if a user is actively engaging with the site by typing a long comment or selecting chec ...