AngularJS promises are known for returning the object itself instead of just the resolved value

function getBusTimetable() {
  var waiting = $q.defer();

  var busData = $http.get('https://bus.data.je/latest');

  busData.success(function(response) {
    waiting.resolve(response);
  });

  busData.error(function(error) {
    waiting.reject(error);
  });

  return {
    getAllTimes: function() {
      return waiting.promise;
    },

    filterByTimetableType: function(type) {
      _data = waiting.promise;
      return _data.filter(function (el) {
        el = el[0];
        return el.MonitoredVehicleJourney.DirectionRef == type;
      });
    }
  }
}

When I call either of the above functions, it returns a promise object with methods like finally, catch, and then, instead of the actual resolved value. How can I correct this behavior?

Answer №1

The best approach is to create your own API that handles promises:

function display() {
    var deferred = $q.defer();

    var data = $http.get('https://bus.data.je/latest');

    data.success(function(_data) {
        deferred.resolve(_data);
    });

    data.error(function(error) {
        deferred.reject(error);
    });

    return {
        all: function() {
            return deferred.promise;
        },

        schedule: function(type) {
            return deferred.promise.then(function (data) {
                return data.filter(function (el) {
                    el = el[0];
                    return el.MonitoredVehicleJourney.DirectionRef == type;
                });
            });
        }
    }
}

You can then use it in this way:

display.schedule().then(function (schedules) { /* interact with the schedules here */ });

Attempting to make promises synchronous retroactively, as mentioned in the comments, is not possible.

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

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Display the preset user coordinates on the map using AngularJS

When a user logs in, I want to display pre-defined coordinates on the map. Here is my map: map.html <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Tem ...

Using React.js to add MongoDB documents into the database

Is there a way to directly insert documents into a MongoDB collection from a React component? I have been working on a personal project, which is a chat web application used for training purposes. For instance, when a user wants to post a new message in a ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

The powers of jQuery and CSS selectors

Previously, I utilized the following code to extract text from the data-placeholder attribute and apply it as a placeholder for my div. [contentEditable=true]:empty:not(:focus):before { content:attr(data-placeholder) } While this method worked well b ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

Issues with data not being successfully transferred between controllers in my service

Presenting my unique service: var CustomService = function () { var filters, charts, subscription; return { getFilters: function () { return this.filters; }, setFilters: function (value) { this.filt ...

Delete a class that is not identified by the DOM

Currently, I'm developing an interactive map that triggers an overlay image to highlight the selected area. I am trying to dynamically add and remove classes from a div based on the highlighted area. Initially, I attempted using the starts with selec ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

The parameter provided should be in the form of a 12-byte string

Hey there, I am facing an issue while trying to delete an entry in my database. Despite attempting JSON.parse on the req.body and rearranging the routes in my routes file, I still can't seem to get it to work. Here is my controller: async function re ...

Exploring the feature of setting the checked state in Radio.Group using Antd

I am dealing with dynamic data that needs to be displayed in a radio button format. One of the challenges is comparing the dynamically generated id with the active radio id and setting it as checked using Radio.Group. Unfortunately, the current code is no ...

What are the steps to convert a canvas element, using an image provided by ImageService as a background, into a downloadable image?

I've been working on an app that allows users to upload an image, draw on it, and save the result. To achieve this functionality, I'm using a canvas element with the uploaded image as its background. The image is retrieved through ImageService. B ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...

Maximizing the performance of plotting hundreds or thousands of series in a 2D scatter or line chart using Echarts

Plotting a large data set with hundreds or thousands of series using Echarts has proven to be slow and challenging to manage. If you take a look at the example code provided in this large and progressive options on single series instead of all plotted se ...

Update the div element without needing to reload the entire page

Is there a way to reload a div tag without refreshing the entire page? I understand this question has been asked before, but I want to make sure I have a clear understanding. <p>click HERE</p> <div class="sample"> <?php functi ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

The function will not be triggered when the form is submitted

I've set up this form to send data to the server-side. It's built in HTML/CSS with AngularJS as well. I made sure that the button is placed inside the form, a common mistake that can cause issues. However, despite my efforts, the function "onAddE ...

What is the best way to send data from a child functional component to a parent class component?

I am facing a situation where I have a parent class component and a child functional component. While there are examples available on passing values from a child class component to a parent class component, I am wondering how to pass a value from this type ...