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

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Unable to modify the appearance of text on the canvas

Trying to customize the font style of canvas text with Press Start 2P The URL has been imported into a CSS file as follows: @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap'); .canvasClass{ font-family: ...

Determining the query count in a MongoDB collection using Node.js

Exploring the world of MongoDb, I have embarked on a project to create a small phonebook application. This application allows users to add and remove entries with a name and phone number. While I have successfully implemented the functionality to add and d ...

Error encountered when parsing JSON data in Vue.js due to presence of invalid characters in the

I have been working on a web application that allows me to upload a JSON file, make changes to it, and then download it. However, the resulting JSON is not valid because certain characters seem to change during the process. Even when I simply upload and do ...

Exploring the art of reading and writing to a file with JavaScript and NodeJS

I am currently working on creating a function that will scan a file and remove all content below a specific line before adding new lines to the file. So far, I have successfully read the file and identified the target line: function analyze() { lineRe ...

Issue with Angular and Karma: HTTP GET request not running

Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework. The challenge I am facing lies in running specification tests tha ...

Can you pinpoint the weak wiring in this AngularJS function?

I am currently studying AngularJS and I suspect there may be a glitch in my page. On the page, there is a TEXTAREA where I have typed 'aaa'. The TEXTAREA is linked to an ng-model named input. The following AngularJS code aims to monitor external ...

Consolidate all scripts into a single file with Asp.net MVC 5 bundling

On one of my razor pages, I have the following script section: @Scripts.Render("~/bundles/script1") @Scripts.Render("~/bundles/script2") @Scripts.Render("~/bundles/script3") The issue is that it renders three separate JavaScript files. Is there a way to ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...

Having difficulties getting basic cube rolling animations to function properly in three.js

I am a beginner in the world of THREEJS and currently working on moving a cube using arrow keys. Take a look at this fiddle: https://jsfiddle.net/mauricederegt/y6cw7foj/26/ Everything is functional, I can move the cube with arrow keys and even rotate it c ...

Tapping on the invisible picture

I currently have a square image of a car with a transparent background. My goal is to make the car clickable so that when I click on it, it triggers an action. However, I also want the transparency around the car to allow clicks to go through and affect th ...

Is it possible to access the Windows certificate store using JavaScript?

Is there a way to access the Windows certificate store using JavaScript? I'm looking to create a web application that can validate user logins by reading their certificates. ...

Unlock the power of nested dynamic content creation with JavaScript

Every time I attempt to use getelementbyid on a dynamically loaded div, I receive null as the result. This occurs even after trying both window.onload = function () { and $(window).load(function() { index.html: <main > <div id="main-div"> ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

Exploring the power of Node.js and EJS through the art of

Recently delving into the world of node.js, I encountered a puzzling issue with my EJS template. It seems that my for loop is not executing properly within the EJS template while attempting to create a basic todo app. Below is the structure of the project ...

What could be causing the directive to not trigger the controller method of mine?

Having trouble with my directive not calling the controller method. Here's the code I'm using: Controller: exports.controller = ['$scope', function($scope) { $scope.addParamter = function () { console.log("here ...

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Ensure that the jQuery datepicker is set with a maximum range of 365 days between the two input fields

Setting Up jQuery Datepicker Inputs I have implemented two jQuery datepicker inputs with default settings as shown below: $("#polis_date_from").datepicker({ uiLibrary: "bootstrap4", changeYear: true, changeMonth: true, dateFormat: "yy.mm.dd", ...

Can you please explain how to indicate a modification in a JSON object with Polymer, transferring information from Javascript, and subsequently displaying child elements?

Currently, I am creating a JSON file that contains a random assortment of X's and O's. My goal is to display these elements in a grid format using a custom Polymer element. Initially, everything works fine as I can see a new grid generated each t ...

JavaScript's replace() method and the $1 issue

My goal is to develop a script that can identify specific patterns within text and then enclose them in particular tags upon identification. $(".shop_attributes td").each(function () { $(this).html(function(i, html) { return html.replace(/E[0- ...