Attempt to generate a function in JavaScript that mirrors an existing one

How can I create a javascript function similar to loadAllOriginal, but with the value of the variable allEmployees being a list of employee objects (ID, FirstName, LastName)? I am attempting to implement this method in combination with autocomplete from the examples provided on this page.

function loadAllOriginal() 
{
    var allEmployees = 'Alabama, Alaska, Arizona, Arkansas, California,   Colorado, Connecticut, Delaware,\
  Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
  Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
  Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
  North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
  South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
  Wisconsin, Wyoming';

    return allEmployees.split(/, +/g).map(function (employee) 
    {
        return 
        {
            value: employee.toLowerCase(),
            display: employee
        };
    });
}

function loadAll()
{
    var allEmployees = $http.post('../Admin/GetUsers/');
    ..........
}

Answer №1

It appears that my previous assumption about your familiarity with loading records into the allEmployees variable was incorrect. I have revised my answer to provide guidance on how to retrieve data from an asynchronous function call and effectively utilize it.

An effective approach is to employ a deferred object and return a promise from the loadAll() function. This can be accomplished using the $q service inherent in Angular. Below is a suggested implementation:

function loadAll() {
    return $q(function (resolve, reject) {
        $http.post('../Admin/GetUsers/').then(function successCallback(response) {
            resolve(response.data.map(function (employee, index) {
                return {
                    value: employee.ID,
                    display: employee.FirstName + " " + employee.LastName
                }
            }));
        }, function failureCallback(response) {
            reject("Error!");
        });
    });
}
var allEmployees = [];
loadAll().then(function success(employees) {
    allEmployees = employees;
}, function failure(message) {
    console.log(message);
    allEmployees = [];
}).then(function (){
    console.log(allEmployees);
    // Additional code utilizing the allEmployees variable should be placed here...
});

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

Issues with Jquery Cycle not functioning as expected

I've been delving into the world of Jquery, attempting to create a basic SlideShow, but unfortunately, the desired effect isn't happening... Here's the layout of my HTML file: <!doctype html> <html lang="en"> <head> ...

Angular's UI router is directing users to the incorrect URL

Just starting out with Angular 1 and tasked with adding a new feature to an existing webapp. The webapp utilizes jhipster for backend and frontend generation (Angular 1 and uirouter). I attempted to create my own route and state by borrowing from existing ...

The onload function in jQuery is not functioning properly when the page is refreshed

I'm just starting out with jquery and I have a simple project in mind. The idea is to have two pictures stacked on top of each other, but I want the page to start showing the second picture first (at a specific scroll point). Then as the user scrolls ...

The Bootstrap modal will not appear when the parent container's position is fixed

I am having an issue with a bootstrap modal that I am using as an instruction guide. My goal is to keep it fixed at the top-right corner of the viewport, so I tried using the fixed position. However, when I do this, the modal turns grey. On the other han ...

Struggling to set up server-sent events and event sources in JHipster

I am currently working on building an application using JHipster 3.5.0 with spring-boot and angular. I want to implement server-sent events to send updates from the backend to the UI, but I am facing issues getting it to work. Below is the code snippet of ...

The draggable=true attribute in EaselJS (MovieClip) canvas does not display a ghost image

I am currently working with a canvas element that contains animations powered by EaselJS. The canvas is wrapped in a parent div with draggable set to true. <div class="outer-parent" draggable="true"> <div class="inner-parent"> <canvas& ...

Difficulty with parsing JSON in JavaScript and retrieving values by key

I'm encountering an error response within the ajax error function; $.ajax(Request).error(function (Response) { var content = JSON.stringify(Response.responseText); var obj = JSON.parse(content); console.log("Response.r ...

TypeORM's Polymorphic Relationship fails to retrieve data from the parent entity

Currently, I am utilizing https://github.com/bashleigh/typeorm-polymorphic for handling polymorphic relations in my model. There are several models involved: // Device Entity @Entity() @TableInheritance({ column: { type: 'varchar', name: 'ty ...

Utilizing a drop-down selection menu and a designated container to store chosen preferences

My form includes a select dropdown that displays available options (populated from a PHP database). Users can choose options from the list, which are then added to a box below to show all selected items. However, I am facing a challenge with the multiple s ...

"JavaScript: Issue Encountered While Converting Hexadecimal to Decimal

I've been working on a custom function to convert hexadecimal to decimal in my Scratch project: function Hex2Decimal(hex){ var deci = 0; var num = 1; var hexstr = String(hex); hexstr = hexstr.toLowerCase(); var expon = 0; for( ...

What are the best practices for implementing optional chaining in object data while using JavaScript?

In my current project, I am extracting singlePost data from Redux and converting it into an array using Object.keys method. The issue arises when the rendering process is ongoing because the singlePost data is received with a delay. As a result, the initi ...

The process of embedding one script into another script is underway

I've been struggling to optimize the loading of a responsive/mobile page, but then I came across a jQuery plugin that dynamically toggles elements based on screen width. This seemed like the perfect solution as it eliminates the need for extra HTTP re ...

Preserving scroll location in Laravel when posting updates

I am facing an issue with the commenting system in my Laravel application. Whenever a user submits a comment, the page reloads and takes the user back to the top of the page. I would like the page to return the user to the same position where the original ...

My Discord.js bot was running smoothly until I added a new command, and suddenly everything went haywire. Can someone assist me in figuring out what went

I recently delved into the world of creating discord bots by following a simple tutorial and customizing it to suit my needs. Initially, the bot worked perfectly fine. However, when I attempted to add the "Mistake" command, it stopped functioning properl ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

I am attempting to send a message via a web socket to the server when a button is clicked: // HelloApp.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button v-on:click="sendMessage($event)">Send Message< ...

Concealing an element by using parentElement.getElementsByClassName to set the display property to none

I am attempting to hide a button that generates a new element upon being clicked (to then be replaced by a delete button), but I'm struggling to set the display property to "none" when trying to target the same element using parentElement and then ret ...

Having trouble assigning a default value to an array in the useState declaration

When attempting to set a default value for my state, I encountered an issue where it was returning undefined. However, upon refreshing the page, the values were correctly assigned to categoryIds. const si = [...searchParams.getAll("cat")]; c ...

What is the best way to check the status of a template file in $routeProvider.then?

$routeProvider.when('/dev/:name', { templateUrl: function(p) { console.log('app.config.js: DEV_MODE TEMPLATE'); return 'Views/Layouts/' + p.name + '.layout.html' }, co ...

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...