Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples:

export default Ember.ArrayController.extend({
    searchText: null,

    searchResults: function(){
            var searchText = this.get('searchText');

            if ( ! searchText)
            {
                return;
            }
            else
            {
                var regex = new RegExp(searchText, 'i');
                return ['hey', 'dude'].filter(function(c){
                    return c.match(regex);
                });
            }
        }.property('searchText')

});

Although this approach works effectively, I encountered difficulties when attempting the same operation with a promise:

export default Ember.ArrayController.extend({
    searchText: null,
    
    searchResults: function(){
            var searchText = this.get('searchText');
            var adapter = AddressBookAdapter.create();
            var companies =  adapter.findAll();

            if ( ! searchText)
            {
                return;
            }
            else
            {
                var regex = new RegExp(searchText, 'i');
                return companies.filter(function(c){
                    return c.match(regex);
                });
            }
        }.property('searchText')

});

Below is the adapter class structure:

export default Ember.Object.extend({
    findAll: function(){
        return ajax('http://localhost:8000/api/v1/address-book/companies')
            .then(function(response){
                return response.data;
            });
    }
});

An illustration of the JSON API response format:

{
  data: [
    {
      id: 6,
      name: "Alexandrine Skiles",
      links: [
        {
          rel: "self",
          uri: "/api/v1/address-book/alexandrine-skiles"
        }
      ]
    },
    {
      id: 33,
      name: "Ally Johns",
      links: [
        {
          rel: "self",
          uri: "/api/v1/address-book/ally-johns"
        }
      ]
    }
  ]
}

The error message received states:

Uncaught TypeError: companies.filter is not a function

I have researched methods to convert a promise into an array for filtering but have not found a solution yet. Any guidance on how to accomplish my objective would be greatly appreciated.

Answer №1

It is not possible to directly change a promise into an array. Promises are objects that represent the eventual completion (or failure) of an asynchronous operation. They hold the potential value that will be available in the future.

When you write the line:

var companies = adapter.findAll();

The companies variable actually holds a promise which, when resolved, will provide your data. In simpler terms, you need to utilize the .then() method associated with promises.

Your ArrayController code should be structured like this:

export default Ember.ArrayController.extend({
    searchText: null,
    searchResults: [],

    searchResultUpdater: function(){
        var searchText = this.get('searchText');
        var adapter = AddressBookAdapter.create();
        var companies =  adapter.findAll();

        if ( ! searchText)
        {
            return;
        }
        else
        {
            var regex = new RegExp(searchText, 'i');
            companies.then(function(data) {
                var results = data.filter(function(c){
                    return c.match(regex);
                });
                this.set('searchResults', results);
            });
        }
    }.property('searchText')
});

This code updates the searchResults property once the promise is fulfilled. Undoubtedly, there are more elegant ways to achieve this using Ember's features.

Additionally, it would be wise to handle the if (!searchText) condition before triggering any ajax requests if the result will not be utilized at all.

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

Having trouble understanding why ng-resource refuses to return an array

I've recently encountered an issue while using AngularJS and NGResource. For some reason, every time I try to use the query function, I receive an empty array in return. Within my controller, the code looks like this: Task = $resource('/tasks&a ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...

Transfer the layout from one HTML file to multiple others without the need to retype the code

I am working on developing an e-commerce website with HTML/CSS. My goal is to have a consistent template for all product pages that are accessed when clicking on a product. However, I do not want to manually code each page using HTML and CSS. Is there a mo ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

Error: The function req.logIn is not valid

I'm currently in the process of creating a dashboard for my Discord bot, but I've encountered an error that reads as follows: TypeError: req.logIn is not a function at Strategy.strategy.success (C:\Users\joasb\Desktop\Bot& ...

To enhance user experience, it is recommended to reload the page once

Hello, I'm looking for a way to automatically refresh the page after submitting an AJAX form. Currently, I have an onClick function that seems to refresh the page, but I still need to press F5 to see the changes I've made. Here's the JavaSc ...

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

The find function within $(this) is malfunctioning

I'm having issues with displaying/hiding content when clicking on a table row. Here is the simplified code snippet: HTML: <table> <tr onclick="showDetails()"> <td>Some text <br> <span class="hiddenC ...

Executing PHP function through AJAX

I have thoroughly researched various resources regarding my issue but still have not been able to find a solution. My goal is to retrieve the result of a PHP function using jQuery AJAX. function fetch_select(){ val_name = $('#name').val(); ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Connecting text boxes with JavaScript and JSON for gaming experience

I am currently developing a game and have encountered a slight issue. Currently, there is a text box in the game that prompts the player to run into it to progress to the next level. When the player does so, the next level loads seamlessly, which works per ...

Using a function parameter to restore the values of an array

Looking to clear an array using a function parameter. Below is my implementation: <script> fruitArray = ["apple", "banana", "orange", "pineapple"] function clearFruitArray(myArr){ myArr = []; ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Incorporating a static image file into a Material UI cardMedia component within a Next.js project

I am struggling to insert a static image into Material UI CardMedia component. I have tried the following code: const useStyles = makeStyles((theme) => ({ media: { height: 0, paddingTop: "56.25%", // 16:9 }, })); <CardMed ...