Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service:

model.getDoohkyById = function( id ){
    if( this.data ) {
        if( this.data.length > 0) {
            for( var i =0; i < this.data.length; i++){
                if( this.data[i].id === id ){
                    //this provides a return value
                    return this.data[i];
                }
            }
        }
    }

    // this provides a promise
    return this.service.getBy('id',id);
}

In what way can I structure the initial return value within the scope of a promise? This way, I can execute it without encountering the error object has no method 'then'?

DoohkyModel.getDoohkyById(this.doohkyId).then( function(result){
      that.doohky = result.data;
});

Answer №1

If you are looking for a way to retrieve data using the $q service, you can utilize the following function (view documentation here):


model.getDoohkyById = function(id)
{
    if(this.data) {
        var deferred = $q.defer();
        if(this.data.length > 0) {
            for(var i = 0; i < this.data.length; i++)
            {
                if(this.data[i].id === id)
                {
                    // Return value
                    deferred.resolve(this.data[i]);
                    break;
                }
            }
        }
        return deferred.promise;
    }

    // Return promise
    return this.service.getBy('id', id);
}

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

Remove a field from a JSON array

Consider the following JSON array: var arr = [ {ID: "1", Title: "T1", Name: "N1"}, {ID: "2", Title: "T2", Name: "N2"}, {ID: "3", Title: "T3", Name: "N3"} ] Is there a way to remove the Title key from all rows simultaneously without using a loop? The r ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

Looking to send an HTTP request to submit a form within a Node.js application to an external website?

Can someone help me with submitting a form on a different site and receiving a response? I'm having trouble figuring out how to do this. Here is the website I am targeting: Below is my code snippet: var http = require('http'); var options ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

I am seeking assistance to utilize Flexbox to completely fill the height of my computer screen

Seeking assistance in utilizing Flexbox to occupy 100% of my computer screen's height, all while ensuring responsiveness: View of my current sign-in page on Chrome (Note the whitespace): Examining my existing frontend code: const SignIn = () => { ...

Is it possible to transfer a value when navigating to the next component using this.props.history.push("/next Component")?

Is there a way I can pass the Task_id to the ShowRecommendation.js component? recommend = Task_id => { this.props.history.push("/ShowRecommendation"); }; Any suggestions on how to achieve this? ...

React application experiencing continuous SpeechRecognition API without stopping

I need assistance with integrating speech recognition into my web application using Web API's speech recognition feature. Below is the React code I am currently working with: import logo from './logo.svg'; import './App.css'; impor ...

Using jQuery to establish a canvas element and define its dimensions by adjusting its width and height attributes

My attempt at using jQuery to create a canvas element was not quite as expected. Here is the code I tried: var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'}); $(body).append(n ...

What is a more effective way to showcase tab content than using an iframe?

I currently have a webpage set up with three tabs and an iframe that displays the content of the tab clicked. The source code for each tab's content is stored in separate HTML and CSS files. However, I've noticed that when a tab is clicked, the ...

Enhance Your User Experience with Primefaces 6.0 Dialog Framework and Frameset

We are currently utilizing a combination of jsf 2.1, primefaces 6.0, and primefaces-extensions 6.0.0, along with mojarra 2.1.7 on weblogic 11g. This is our first time using primefaces 6.0, primarily because of the nested dialogs requirement. Upon opening ...

Ways to execute additional grunt tasks from a registered plugin

I am currently in the process of developing a custom Grunt plugin to streamline a frequently used build process. Normally, I find myself copying and pasting my GruntFile across different projects, but I believe creating a plugin would be more efficient. Th ...

What is the best way to display a page within a div when clicking in Yii?

I'm trying to use the jQuery function .load() to load a page into a specific div. Here's my code: <a href="" onclick="return false;" id="generalinfo"> <div class="row alert alert-danger"> <h4 class="text-center">Gen ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

What steps can I take to update this HTML document and implement the DOM 2 Event Model?

I'm struggling with converting my document from the DOM 0 Event model to the DOM 2 Event model standards. I've tried getting help from different tutors on Chegg, but no one seems to have a solution for me. Hoping someone here can assist me!:) P. ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

Customizing data from AJAX responses

Using PHP, I am receiving data as an object and passing it through a mustache template to create a table. My inquiry is about controlling the row breaks for my data. Is there a way to insert a <tr> after every 3 <td> without using JavaScript? Da ...

Is there a simpler method to examine scope in Angular when debugging?

During my Angular sessions, I often catch myself repeatedly performing the following steps: Choosing an HTML element in the "elements" tab of dev tools Executing scope = angular.element($0).scope() Is there a simpler way to accomplish this task? Maybe a ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...