How can I initialize an empty promise using AngularJS?

I am looking for a way to achieve the following:

var promise = IAmAEmptyPromise;

if(condition){
    promise = ApiService.getRealPromise();
}

promise.then(function(){
    //perform some actions
});

I want to define a promise that can be resolved with a then function. However, this promise might get replaced by another promise that returns some data. After that, I would like to resolve the promise regardless of whether it has any data or not. Is this feasible? My attempt was:

var promise = $q.defer().promise;

if(!$scope.user){
    promise = UserService.create(params);
}

promise.then(function(){
   //handle the scenario where a new user is created or an existing user is found
});

The above code does not work as expected when a user already exists. Any suggestions on how to make it work in all cases?

Answer №1

As Bixi mentioned, you have the option to utilize $q.when(), which allows you to encapsulate a promise or a value within a promise. When you pass a promise into when(), it will be returned as is. If a non-promise value is passed, a new promise will be generated and resolved immediately with that value. Here is an example:

var promise;
if(!$scope.user){
  promise = UserService.create(params);
} else {
  promise = $q.when($scope.user);
}

promise.then(function(user){
  //The user will either be newly created or already exist.
});

Answer №2

Utilizing native es-6 promises allows you to easily generate an instantaneously resolved promise by using Promise.resolve(). This feature proves to be beneficial when chaining promises together.

var p = Promise.resolve();
for (var i=0; i<something.length; i++) {
    p = p.then(UserService.create(newUsers[i]));
}
p.catch(function(e) {
    console.error('oops: ', e);
}).then(function() {
    console.log('done.');
});

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

The absence of the 'Access-Control-Allow-Origin' header on the requested resource is causing a supersonic issue

Just getting started on my first hybrid application with AppGyver's Supersonic. The $http request in Angular works great on the iOS emulator. $http.get('http://localhost:3000/api/get_data').success (data, status) -> console.log data H ...

Utilize the power of Bootstrap Modals to enhance your form validation with a seamless integration of Jquery

I have a few questions about JQuery syntax: 1) The modal is not showing up. Could this be related to an operator (&&) issue? How can I fix it? It should only appear if the input is valid. 2) How do I combine preventDefault with valid classes when submitt ...

Do you have any suggestions on how to implement AJAX functionality on a website like this?

We have successfully created a comprehensive website with various pages, each offering unique features. For example, our galleries page utilizes jQuery Colorbox for viewing images, while other pages do not require this plugin (such as the 'About Us&ap ...

An in-depth guide to effectively unit testing a Node.js Express application

Looking to kickstart unit testing in my Node Express project. What's the most straightforward and convenient approach for this? ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

An effective method for retrieving textarea data in Node.js

I am facing an issue where I cannot successfully send data from a <textarea> to Node.js. It seems that the data I'm trying to send is not being received by Node.js. To retrieve data in Node.js: continueBtn.addEventListener("click", ...

Expanding a dropdown list on the fly using vanilla JavaScript

I am restricted to using Vanilla JavaScript only, without any additional libraries like jQuery. Initially, I attempted to store all registered items in a global array and then use a forEach loop to append an <option> child to the <select>. How ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

SSL-enabled Websocket server powered by websocket.io

I have built a basic Websocket server using node.js and websocket.io var ws = require('websocket.io') , server = ws.listen(8000); server.on('connection', function (socket) { console.log("connected"); socket.on('message&ap ...

What could be causing the issue with my code where the canvas is not showing boxes beyond a y-coordinate of 8 along the x-axis?

I've been working on creating a 64 square checkerboard using the html canvas element in javascript, but I'm encountering an issue. The boxes aren't rendering properly after the first 8 squares on the y-axis, and I can't figure out where ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

RangeError: The React application has surpassed the maximum stack size limit, causing an error to be thrown

Hey there, I could use a hand. I'm fairly new to React and attempting to develop an application for managing contacts by adding them to Local Storage and deleting them. Below is the code snippet from my App.js file: import React, {useState, useEffect} ...

A recursive function in Javascript that utilizes promises

Utilizing HTTP calls to an embedded webserver, the function below is designed to delete files. The webserver accepts the DELETE verb for file deletion and works on empty folders as well. I brainstormed a function that recursively retrieves folder contents ...

The choice between invoking a function within a route handler or employing a middleware for the task

I am currently exploring a potential difference in coding approaches. Let me illustrate this with an example excerpted from the express documentation: https://expressjs.com/en/guide/using-middleware.html function logOriginalUrl (req, res, next) { console ...

The inner workings of JavaScript functions

I am curious about how JavaScript functions are executed and in what order. Let's consider a scenario with the following JavaScript functions: <span id=indicator></span> function BlockOne(){ var textToWrite = document.createTextNode ...

Displaying the Status of a Script that is Running Asynchronously

My script takes around 5 minutes to complete and sends an email with a file attachment once finished. The entire process happens on a single PHP page without using AJAX. I want the front end to handle form submission seamlessly, processing the request in ...

Exploring the Distinctions Among Express Router, Module Export, and App.Use() in Node and ExpressJS

I am working with app.js, where the code looks like this: var express = require('express'); var report = require('./routes/Report'); var app = express(); app.use('/api/appReport', report); app.listen(3000); module.exports ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

https://i.sstatic.net/j76vM.pnghttps://i.sstatic.net/EQPZO.png I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...