Setting a promise value for an object's method

Imagine this object I am constructing.

$scope.formules = {};
$scope.formules = {

    label: 'some label',
    getYear: function() {

        // getData() is a promise
        $scope.getData().then(function(){

            // Some code to fetch the correct data

            return someData;

        }.catch(function () {
         $scope.error = 'bad error';

    }

}();
}

Currently, getYear is undefined because I need to include a second return.

$scope.formules = {};
$scope.formules = {

    label: 'some label',
    getYear: function() {

        // getData() is a promise
        $scope.getData().then(function(){

            // Some code to fetch the correct data

            return someData;

        }.catch(function () {
         $scope.error = 'bad error';

    }

    return $scope.getData();  //Adding the second return here

}();

Alternatively, you could do it in a shorter way like this:

$scope.formules = {

    label: 'some label',
    getYear: function() {

        // getData() is a promise
        return $scope.getData().then(function(){ // Or adding the second return here.

            // Some code to produce the right data

            return someData;

        }.catch(function () {
         $scope.error = 'bad error';

    }


}();

However, this approach isn't ideal as the second return only returns the promise, making my method getYear contain a promise instead of the desired value.

One more attempt:

$scope.formules = {

    label: 'some label',
    getYear: function() {

        // getData() is a promise
        return $scope.getData().then(function(){ // return the $scope.getData()

            // Some code to produce the right data

            return someData;

        }.catch(function () {
         $scope.error = 'bad error';

    }


}().then(function(data){ return data; });

Even after trying multiple ways, console.log($scope.formules) still shows that getYear is a promise and doesn't provide the actual value.

Note: When using console.log(data) instead of return data;, I am able to retrieve the desired value for binding to the method.

What am I missing here? What is the correct way to bind the value? Neither Stack Overflow nor Google has provided me with an answer...

EDIT

Here is the exact code segment used inside the method:

getYear: function ()  {

    $scope.measure = value.formules_total_year;

    $scope.getCube().then(function(test){

        var totalRatioData = [];

        for (var i = 0; i < $scope.tempData.length; i++){

        totalRatioData.push($scope.tempData[i][1].qNum);

    }

    return totalRatioData;

})


}(),

$scope.tempData is an array containing 5 arrays.

[Array[2], Array[2], Array[2], Array[2], Array[2]]
with each array consisting of 2 objects.

0: Object
    qElemNumber: 0
    qNum: 2009
    qState: "O"
    qText: "2009"
    __proto__: Object
1: Object
    qElemNumber: 0
    qNum: 225632.21000000002
    qState: "L"
    qText: "225632,21"

In this edited version, I aim to create a new array by extracting all the qNum values from the last object of the 5 arrays and assign this array to getYear.

Answer №1

It may be a challenge to grasp the end goal of bundling all the $scope assignments in your getYear() function and why you are doing so. It seems like you are attempting to make an asynchronous value (totalRatioData) synchronous, which is not possible with es5. The upcoming es7 will introduce a new method called "await" that could facilitate this.

If you wish to utilize the value of getYear on your view, simply pass the promise's value to your view model ($scope variable).

// Initialize controller
$scope.year = null;
_initYears();
    
function _initYears() {
  
  $scope
    .getData()
    .then(
      function() {
        
        var totalRatioData = [];

        for (var i = 0; i < $scope.tempData.length; i++){

          totalRatioData.push($scope.tempData[i][1].qNum);

        }
        
        // Assign data to year
        $scope.year = totalRatioData;
        
      }  
    )
  ;
}

If you are using ui-router, it is advisable to place your promise in the appropriate section of your state configuration to ensure it is resolved before the state is activated.

I hope this information proves helpful.

Answer №2

It is advisable to fetch data in the controller instead of within your scope properties.

function myController($scope, someService) {
    $scope.info = { type : 'type' };
    someService.retrieveData().then(function(data) {
      $scope.info.details = getDetails(data);
    });
}

After that, bind to the scope properties

<span ng-bind="info.type"></span>
<span ng-bind="info.details"></span>

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

presenting JSON data in a table format accurately

I recently created an ajax function that sends a get request to an API and retrieves JSON data, which I then display in a table. Here is what I have attempted: <script> function getInfo() { $.ajax({ type: "GET", url: "http: ...

Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/ I have multiple line segments with unique IDs, and I know which ones intersect. My goal is to create new arrays that only contain the IDs of the overlapping line segments. I do not need the IDs of l ...

Cherrypy/Chrome: Issue with jquery ajax request remaining pending after several successful requests

My current project involves a Cherrypy server that receives a JSON array from a client via AJAX call. The server then manipulates the array and sends it back to the client. However, I've noticed an issue where after a few smooth requests, the next req ...

Indicator count for multiple slick carousels

Is there a way to create individual slide counters for multiple sliders that do not work together? In my current example, the slide counters are functioning together: https://codepen.io/anon/pen/oqqYjB?editors=1010 <div class="container"> <div ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Proper method for incorporating client-side libraries (such as adminLTE) into Vue.js 2.0

Looking to merge adminLTE with vue. I've set up a fresh app using vue create admin-cli Next, I ran npm install admin-lte --save following the instructions in this link: Now npm is storing everything under node_modules/admin-lte I'm not quite ...

Multipart Express - { [Error: transfer-encoding not recognized] status: 400 }

Encountering the { [Error: unknown transfer-encoding] status: 400 } error from the multipart module in the express 3 framework. It appears that the TE header should be sent, but it is not. Some sources mention that this header may conflict with the content ...

Enhance Your Website with a jQuery Plugin for Dynamic Updates to ElementsgetPost

Is there a way to update the content inside an element by passing a new value to the public method updateText? Currently, when I try to pass a new string to the updateText method and click the button, only the method name is received as an argument instea ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

Issue with AngularJS toggle being obstructed by Math operation

I am facing an issue with my table rows where cells are being filled with words from an API. I have implemented a feature that allows users to toggle the selection of a cell. To achieve this, I am using ng-class={selected:toggle} and ng-click="toggle = !to ...

Tips for resolving the error message 'Object(...) is not a function' when using ref().set() with Firebase

While attempting to include custom information for a newly registered user in Firebase, I encountered an issue where the ref().set() function is being identified as not a valid function. What could be causing this problem? I have verified that the syntax ...

Converting SHA1 function from JavaScript to Python

Can you help with translating this Javascript code to Python? def sha1(str1, raw): hexcase = 0 chrsz = 8 str1 = utf16to8(str1) def utf16to8(str): out = "" len = len(str) i = 0 while i < len: ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

What is the proper way to utilize the uppercase method while ensuring that Turkish characters are not permitted?

Here is the code snippet I am working with: <input type="text" style="text-transform: uppercase" /> When using this code, characters like ü are transformed to Ü. However, I want ü to be transformed to U, so for example, Gülay should become GULA ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

What is the best way to add uppercase letters exclusively?

Is there a way to dynamically style uppercase text within an <h2> tag that is generated based on an image's alt text? I'm thinking of using javascript / jquery to identify the uppercase text and encase it in a <strong> tag, then appl ...

Exploring the World of D3.js with an Interactive Example

Struggling to grasp D3, I'm having difficulty executing the circle example. http://mbostock.github.com/d3/tutorial/circle.html I aim to run the part where the circles change colors and sizes. I simply copied and pasted the example but can't fi ...

Tips for sending a second parameter in a onSubmit function call in ReactJS

Below are the code snippets import React from "react"; var exampleComponent = React.createClass({ handleSubmit: function (e, text) { e.preventDefault(); console.log(text); }, render: function () { return ( ...

Exporting JSON blend files in Three.js is causing an error that says "Cannot read property 'type' of undefined."

Trying to display the default 3D cube template from Blender v2.74 in Chrome browser, I exported it as json using the threejs v1.4.0 add-on and I'm using Three.js revision 71. Referencing the documentation at , I attempted to load this json model stor ...