Create a Promise that guarantees to reject with an error

I am relatively new to utilizing promises, as I typically rely on traditional callbacks. The code snippet below is from an Angular Service, but the framework doesn't play a significant role in this context. What really matters is how to generate a promise that guarantees to throw a specific error. Here is how it would look with callbacks to handle this situation:

var client = algolia.Client('ApplicationID', 'apiKey');


var indices = {

    users: client.initIndex('users'),
    topics: client.initIndex('topics')

}

return {

   search: function(indexName, searchTerms, cb){
       var index = indices[indexName];

       if(index){
          index.search(searchTerms).then(function handleSuccess(msg){
               cb(null,msg);
            }, function handleError(err){
               cb(err);
            }
       }
       else{
          cb(new Error('no matching index'));
       }

   }

...but when trying to convert the above to solely use Promises, I find myself unsure of the approach:

var client = algolia.Client('ApplicationID', 'apiKey');

var indices = {

    users: client.initIndex('users'),
    topics: client.initIndex('topics')

}

return {

   search: function(indexName, searchTerms){
       var index = indices[indexName];

       if(index){
          return index.search(searchTerms); //returns a promise
       }
       else{
          //how can I create a promise that will result in throwing an error when there's no matching index?
       }

   }

Although there are various ways to restructure the code to tackle this issue, I am interested in exploring a direct solution.

Answer №1

To handle cases where no matching index is found, simply return a rejected promise using $q.reject(err):

return {

   search: function(indexName, searchTerms){
       var index = indices[indexName];

       if(index){
          return index.search(searchTerms); //this returns a promise
       }
       else{
          // return a rejected promise when there is no match
          return $q.reject(new Error("no matching index"));
       }
   }

For more information, refer to the documentation here.

Answer №2

To handle errors, you can utilize the $q service and use $q.reject(reason). For example:

return $q.reject('NO_INDEX');

According to the $q documentation:

This creates a promise that is resolved as rejected with the specified reason.

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

Update the radio button to display the value entered in the text input field

I'm trying to implement a feature where the value of a text box can be set as the value of the selected radio button. Below is the code I have: HTML <form action="add.php" id="registration" method="post" name='registration' onsubmit="re ...

Generate a hard copy of the data table row without needing to view it beforehand

Here are some records from a table: +--------+---------+-------+----------+--------+ | Name | Address | Phone + Email | Action | +--------+---------+-------+----------+--------+ | Andy | NYC | 555 | <a href="/cdn-cgi/l/email-protection" cl ...

Incorporate the latest value into an array of objects using JavaScript, taking into account its frequency

Hey there, I have an array of objects where I need to add a new property or value to each object based on its order number occurrence. For example, in the array of objects, there is a property called order number. If an object contains the highest order n ...

Guide on transitioning from a WebGL renderer to a canvas renderer in three.js

My goal is to display a scene using either a WebGL renderer or a canvas renderer in three.js (version 69). This is the code I am using: <!DOCTYPE html> <html> <head> <script src="./libs/three.js"></script> <scri ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

AngularJS routing not rendering the correct view

I'm encountering a routing problem with my AngularJS/ExpressJS application. The issue is that login.ejs and signup.ejs are partial views, while welcome.ejs serves as the main template. The intention is for these views to load in a ui-view container wi ...

Troubleshooting CSS override issues when swapping components in ReactJS

Access.js import React from 'react' export default class Access extends React.Component { componentWillMount(){ import ('./styles/access_page.css'); } .... <Link to="/new-account">Sign Up</Link> } Cr ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Parent scope receives directive updates with a slight delay

I recently made a transition of my simple paging feature from the controller to a directive, but encountered a peculiar issue. Whenever I update the parent scope from within the directive, the changes only reflect on the next alteration. For instance, if t ...

"Trouble arises when event listener fails to function following an append operation

Recently, I delved into the world of HTML/CSS and jQuery in an attempt to create a simple web game. Below is a snippet of my HTML code: function playGame() { var theLine = "<div id = \"line\">"; for (var i = 0; i < 9; ...

Is each individual character displayed on the web page twice when using a controlled component?

Currently, I am diving into the extensive React documentation. A particular section caught my attention - controlled components. It delves into how form elements, such as an <input>, manage their own internal state. The recommendation is to utilize c ...

Spinning Loader in ui-select AngularJS

Currently, I am working with AngularJs and the ui-select plugin from ui-select. My goal is to implement a spinner while fetching data from the server. How can I integrate a spinner directly into the HTML code? The following snippet shows the existing HTML ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

Ways to avoid altering values within $watch blocks

I'm currently monitoring a variable in my code that can be modified by the user through an input field. My goal is to ensure that the new value entered by the user is always a number and if it's not, I want to retain the previous value until a co ...

The rotation feature for legends in Highcharts does not function properly on Internet Explorer 10 and 11 if the document mode is

When using Internet Explorer 10 or 11, rotation works perfectly fine if we select edge mode, as shown in the image. This information was taken from the High Chart Demo Charts. However, if we select Document mode 8 in IE 10 or IE 11, the rotation does not ...

Retrieve a remote text file using vanilla JavaScript instead of relying on jQuery

Currently, I am aiming to retrieve the content of a text file using JavaScript for parsing purposes. Although I previously relied on jQuery and JSONP for this task, I now prefer to achieve it without any framework. Despite numerous attempts, none have bee ...

Issue with Material-UI Slider not updating the color of the active range

I am currently working on a Range Slider component that ranges from zero to ten. The issue I am facing is that the values inside the range are not getting colored as expected. Here is My Custom Slider Component: export function VoteRange({ voteRange, set ...

Refreshing a React page will lead to props being empty

The situation I am facing is that the code appears to be correct, but for some reason, when the web page loads, this.props.items does not seem to be passed to Item. Strangely, when I attempt to display this.props.items in console.log, nothing shows up. How ...

Can you tell me the JavaScript alternative to Jquery's .load() shortcut method?

Exploring the modernized version of jquery, specifically the .load() ajax shorthand method that is not deprecated. One example to consider is finding the javascript equivalent for the traditional jquery ajax shorthand method mentioned below: $("#targetdi ...

Using Next.js for dynamic routing with JSON arrays in getStaticPaths

I am currently facing an issue while trying to incorporate a json file with multiple arrays into my Next.js application. The structure of the json file is quite complex, and I'm unsure about how to convert it into a format that can be effectively util ...