Receiving the Outcome of q's Decision - Resolving or Rejecting

I found an interesting example involving $q on the book Mastering Web Application Development with Angular.

In this code snippet, I am curious about how to obtain the String result of either

pizzaOrderFulfillment.resolve(...)
or pizzaOrderFulfillment.reject.

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function ($scope, $q) {

    var Person = function(name) {

        this.eat = function(food) {
            return name + " is eating " + food;
        };

        this.beHungry = function(reason) {
            return name + " is hungry because" + reason;
        };
    };

    // success
    var pizzaOrderFulfillment = $q.defer();
    var pizzaDelivered = pizzaOrderFulfillment.promise;

    var man = new Person("man");

    pizzaDelivered.then(man.eat, man.beHungry);

    pizzaOrderFulfillment.resolve("chicken");
    // TODO: var successResult = "man is eating chicken"
});

Answer №1

To handle your assignments effectively, it is recommended to place them within the promise callbacks:

pizzaDelivered.then(
  function(food) {
    $scope.successResult = person.eat(food);
  }, 
  function(reason) {
    $scope.failureResult = person.beHungry(reason);
  });

Subsequently, in an Angular context, you can utilize these scope variables within your views and they will only display after the promise has been fulfilled:

{{successResult}}
{{failureResult}}

Check out the Demo

Answer №2

Due to the asynchronous nature of resolve and reject, it is important to set any resulting variables within a callback:

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function ($scope, $q, $log) {

    var Person = function(name) {

        this.eat = function(food) {
            return name + " is eating " + food;
        };

        this.beHungry = function(reason) {
            return name + " is hungry because" + reason;
        };
    };

    // success
    var pizzaOrderFulfillment = $q.defer();
    var pizzaDelivered = pizzaOrderFulfillment.promise;

    var man = new Person("man");

    var successResult = null;
    pizzaDelivered.then(function(food) {
        successResult = man.eat(food);
    }, function(reason) {
        successResult = man.beHungry(reason);
    }).finally(function() {
        $log.info("successResult: %s", successResult);
        $scope.output = successResult;
    });

    pizzaOrderFulfillment.resolve("chicken");
});

See it in action here: http://plnkr.co/edit/VLa2qcD4XUDcO3Wo8mUl?p=preview


I've created another example that showcases the asynchronous behavior of $q using $timeout. It includes two promises, one being resolved and the other rejected: http://plnkr.co/edit/Rq715C7NmhvXnao2i9xy?p=preview

Answer №3

When discussing promises, the concept of adding callbacks (using then) that get triggered upon rejecting or resolving the deferred object becomes important.

In this scenario, it is crucial to assign the variable inside the promise.

var myApp = angular.module('myApp',[]);

myApp.controller("MyCtrl", function ($scope, $q) {

    var Person = function(name) {

        this.eat = function(food) {
            return name + " is eating " + food;
        };

        this.beHungry = function(reason) {
            return name + " is hungry because" + reason;
        };
    };

    // success
    var pizzaOrderFulfillment = $q.defer();
    var pizzaDelivered = pizzaOrderFulfillment.promise;

    var man = new Person("man");

    // This was commented out just so you can see this example.
    //pizzaDelivered.then(man.eat, man.beHungry);

     var successResult = null;
     pizzaDelivered.then(function(food){
         successResult = man.eat(food); // var successResult = "man is eating chicken"
         console.log(successResult);
     });

   // You can add more callbacks to "pizzaDelivered" using commas as you did in your main example.

    pizzaOrderFulfillment.resolve("chicken"); // after resolving the defered object the callbacks are suppose to run.
});

Check out this Fiddle for more information.

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

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

transferring background-image in html between elements

Imagine having a three-level hierarchy HTML code structured like this: <section> <div id="outer"> <div id="inner"> </div> </div> </section> If we set background-image:someImage.jpg to the section, and backg ...

Delay in Response of OnTextChanged Event in ASP.NET

The functionality is there, but it doesn't respond immediately. It only works when I click on something. I attempted using the onkeyPress method as well: <asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress" ></asp:TextBox& ...

When a npm package consists of multiple files, what is the best way to import them?

I have an npm package that consists of three files in the dist folder, generated by webpack: https://i.sstatic.net/td5Us.png Within the package.json file, I have designated the sample.js file as the main one: "main": "dist/sample.js", ...

What is the best way to ensure a bottom tooltip stays perfectly aligned with the right edge of its corresponding element?

Currently, I am trying to implement a tooltip above my progress bar. However, the small tooltip that I have is not functioning correctly... This is how it currently appears: https://i.sstatic.net/ZJUyT.png I need the tooltip to display above the white d ...

Learning to implement the ng2-chart.js directive within Angular 2

I recently installed ng2-charts through npm First, I ran npm install ng2-charts --save and npm install chart.js --save After that, I included the following code in my index.html file: <script src="node_modules/chart.js/src/chart.js"></script> ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

Nuxt.js implemented with Auth using jwt refresh tokens

I've implemented the Auth library in my Vue/Nuxt project and have successfully set up JWT Authentication. However, I'm encountering an issue with the refresh token. The refreshToken cookie is consistently being set to null: https://i.sstatic.ne ...

Node.js and Couchbase integration: A closer look at the functionality of the add() method

As I dive into learning about couchbase, I encountered a basic issue with inserting data using the add() method in my couchbase instance. Despite troubleshooting, something seems amiss in my code and I'm unable to pinpoint the exact reason. var http ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

The ng-repeat-start feature is not functioning properly across different levels

I am attempting to utilize the ng-repeat-start directive in order to construct a table that resembles the following: https://i.sstatic.net/Qgc91.png The structure of my JSON data is as follows: [ { "name": "Chapter 1", "parts": [ { ...

Execute functions in a random order

My array contains a series of functions and is structured as shown below: var all_questions = [ show_question(1, 1), show_question(2, 1), show_question(3, 1), ]; I'm interested in executing those functions within the array in a random or ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

Discover the smallest and largest values within the multi-layered object

My JavaScript object is deeply nested with an infinite number of children, each containing a value. var object = { value: 1, children: { value: 10, children:{ value: 2, children: {...} } } } I've tried ...

Obtain the GMT date for the next day

Need help with code to get the current date and the current date + 1 day (in GMT). var now = new Date(); var newexp = (now + 3); var show = newexp.getGMTString(); alert(show); Goal is to set a cookie to expire in 1 day. function SetCookie(name, value, ...

The callbacks in NextAuth do not appear to be functioning

I am currently working on implementing authentication with NextAuth in my Next.js app. I've noticed that the callbacks from the GoogleProvider are not being executed. Even after adding a console log statement, I cannot see any output in the console. A ...

How can you customize the appearance of the filledInput component within a TextField component in Material UI?

I need some guidance on how to change the color of the FilledInput component within a TextField. Unlike InputProps, FilledInputProps are not directly accessible for styling with classes. Any suggestions on how I can customize the styling of the FilledInpu ...

How to Use ng-controller in AngularJS to Submit a Form with PHP

Hey there! I'm diving into AngularJS and PHP for the first time. My current project involves creating a Contact Form using AngularJs and PHP. The form is pretty straightforward, requiring users to input their First Name, Last Name, Email, and Message. ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

Vue.js: Synchronization of props may not happen instantly

Struggling with using vue.js to synchronize a prop between parent and child components. The challenge is that sync relies on events, so every time I update the value, I have to wait for $nextTick before seeing the update. It's cumbersome to include $n ...