A JavaScript tool that facilitates the auto-resolution of objects when working with promises, ideal for frameworks such as Angular's

Angulars $resource is equipped with a fantastic feature that allows objects to automatically update views by injecting values. Inside the $resource service lies a Resource object where the resolved result is copied using shallowClearAndCopy().

I am interested in chaining the promise returned from a $resource to achieve something similar to having the deferred result injected into a Resource object.

var otherProperty = 'somethingChanging';
var lazyUser = $resource('/user/:userId').get({id:id});
var userDisplayNamePromise = lazyUser.$promise.then(transformResult);
function transformResult(user){
  return { displayName: user.firstname + ' ' + user.lastname,
           other: user[otherProperty]
         };
}

Currently, I have to manually update the display user like this:

userDisplayNamePromise.then(updateDisplayUser);
function updateDisplayUser(displayName){$scope.user = displayName;}

But ideally, I would prefer to do something like:

$scope.user = something(userDisplayNamePromise);

I have not found an easy way to handle promises in this manner. Does anyone have any helpful suggestions?

I have included a basic working example on github.com/burka/resolvling. However, it's hard to believe that nobody has done this before?

Answer №1

There are established methods for altering the response of an angular resource.
Check out this demo
Refer to the official documentation

transformResponse – {function(data, headersGetter)|Array.} – This is a function or an array of functions used to transform the http response body and headers into a modified (typically deserialized) format. By default, the transformResponse contains one function that checks if the response resembles a JSON string and deserializes it using angular.fromJson. To avoid this behavior, set transformResponse to an empty array: transformResponse: []

Here is a sample code snippet

angular.module('services', ['ngResource']).
factory("someService", function ($resource) {
    return $resource(
        '/', {}, {
        get: {
            method: 'GET',
            transformResponse: function(data, headers){
                //MODIFYING THE DATA
                data = {};
                data.coolThing = 'BOOM-SHAKA-LAKA';
                return data;
            }
        }
    }

    );
});

Answer №2

Uncovering promises is a regular practice in handling asynchronous operations and should be acknowledged as a necessity.

The idea of self-populating objects in $resource goes against the norm in asynchronous workflows, and depending on its usage, it might be viewed as an anti-pattern.

It's not feasible because displayName is meant to be a singular value:

$scope.displayName = something(userDisplayNamePromise);

However, this is something that $q promises struggle with without extensive adjustments (as shown in the repository):

$scope.displayObj = something(userDisplayNamePromise);

Although it may function for object bindings like {{ displayObj.name }}:

$scope.displayObj = userDisplayNamePromise.$$state.value;

Using this approach in a production environment is not recommended - not only due to the fact that internal $$ properties should be avoided, but also because $$state.value could contain a value for a rejected promise.

In an ES6 or Babel-transpiled ES5 setting, co and generators can be utilized to streamline promises:

var wrap = (fn) => {
  return function(...args) {
    co(fn.bind(this, ...args));
  }
}

app.controller('AppController', ['$scope', '$q', wrap(function* ($scope, $q) {
  this.name = yield $q.resolve('World');
})]);

For ngRoute and UI Router, utilizing route resolvers can inject resolved values into controllers and bind these values to the scope, offering a common solution to avoid unwrapping 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

Sending an object as a prop in React component

I have a function class: function TopicBox({topicName, article1}) { return ( <div className="TopicBox"> <h1>{topicName}</h1> <div className="topicDivider" /> <Ar ...

Adding hyperlinks that do not redirect

I have 2 separate divs displayed on a website: <button class="form-control margin btn btn-warning hide_all" id="addLinks">Link Pages</button> <button style="display: none" class="form-control margin btn btn-primary hide_all" id="hideLinks"& ...

What is the best way to update objects in different scopes within AngularJS?

Exploring AngularJS for the first time, I find myself struggling with understanding scopes. My current dilemma involves modifying an object or variable from multiple scopes. Here's the scenario: I'm looking to centralize the user notification Co ...

(JS) utilizing an external .js function by using the <script> tag

Looking to execute the function cookiefix() from main.js, which is linked at the bottom of my HTML file. echo '<body>'; if(!isset($_COOKIE['clicked'])) { if(!isset($_COOKIE['count'])) { echo '<script type="text/ ...

Trouble with Automatically Updating ObjectID in MongoDB using Node.js

My attempts to update the "ObjectId" from the front-end to my database have been unsuccessful. Adding new data from the UI works perfectly, but updating existing data does not. I've exhausted all options without success. Any assistance would be greatl ...

Merging Technology: Integrating Maps into Hybrid Applications

Currently, I am developing a mobile application using React-Native with a main focus on: Map Integration: Partial Success - I have successfully implemented all features mentioned in this link. The remaining task is to display live routing based on curren ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

What is the process for "unleashing" the X Axis following the execution of chart.zoom()?

After setting the scroll strategy to setScrollStrategy(AxisScrollStrategies.progressive), I noticed that my chart was scrolling too quickly due to the fast incoming data. To address this, I decided to set a specific initial zoom level for the chart using c ...

Achieving closure by fulfilling the previously fulfilled promise once more

I have a situation while using $q in AngularJS. If I create a single promise that is already resolved, is it possible to resolve it again? I am unsure if this is feasible, but if not, is there any method by which I can resolve the same promise repeatedly ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...

Add Text to HTML and Delete Added Content Upon Button Click

I have successfully implemented code that appends new content to the div "users". However, I am facing an issue with removing the appended content when a user clicks a button. Currently, the code only removes the "remove" button upon clicking. But I need ...

Is it possible to make the v-toolbar-title fixed within a v-navigation-drawer using Vuetify?

Can the <v-toolbar-title> be fixed within a <v-navigation-drawer>? <v-card class="d-inline-block elevation-12"> <v-navigation-drawer hide-overlay permanent stateless height="440" value="true"> <v-toolbar color="whi ...

Setting up a NodeJS project (built with Express and Angular) on a Ubuntu Cloud Server with NGINX hosting

I have a domain and a cloud server (running Ubuntu 16.04 OS), and I am attempting to host a nodeJS project (using ExpressJS and AngularJS) on the cloud server. Currently, I have installed Node.js and Nginx on my cloud server. My application is running loc ...

Error: The element at point (713, 6) is currently not clickable due to an unknown issue. Another element, specifically the container with class "container," is blocking the click

I am experiencing a strange error. During my test, I navigate to angularjs.org first. Next, I use sendKeys() on an input field named "JavaScript Projects" that has filters. Then, I click on a checkbox to mark a todo item as Done. However, when performing t ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

Is there a way to implement a local gltf loader in three.js to display on a GitHub server within my repository?

Every time I run code on my VS app, it works perfectly fine. However, when I try running it on GitHub, it shows an error 404 and gets aborted. I came across some documentation regarding this issue, but I'm having trouble understanding it. Check out ...

What are the steps to disable CSS in order to speed up the execution of automation tests?

Source: What is the optimal method to temporarily disable CSS transition effects? When testing JavaScript, I typically utilize JavascriptExecutor, however, none of the aforementioned blogs shed light on how this can be achieved. I attempted: js.execu ...

What could be the reason for the `controller.$render` method not being triggered as intended?

Check out this code snippet on plnkr.co. Within the link function of the directive, calling controller.$render() was successful. However, when attempting to override the controller.$render function, it does not execute as expected. The statement console.lo ...

Conceal the href element within a designated UL using JavaScript

Is there a way to only hide the href element in a specific UL element, rather than hiding all href elements with the same class name? Let's consider an example HTML code: <ul class="UL_tag"> <li>Text 1</li> <li>Text 2< ...

Looping through JavaScript to generate HTML code

I have come across a HTML code snippet that looks like this: <div class="content"> <article class="underline"> <a href="incidente.html"><img id="incidente" src="img/buraco.jpg" alt="Incidente" /></a> ...