Transfer the output to the second `then` callback of a $q promise

Here is a straightforward code snippet for you to consider:

function colorPromise() {
  return $q.when({data:['blue', 'green']})
}

function getColors() {
  return colorPromise().then(function(res) {
     console.log('getColors', res)
     // perform some action with res
  };
}

function testGetColors() {
  getColors().then(function(res) {
    if (angular.equals(res, {data:['blue', 'green']})) {
      console.log('passes')
    }
  });
}

Explore this Plunker: http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
In the provided example, the value of res in the testGetColors function happens to be undefined.

What can be done to successfully pass res to the second then function within the $q promise?

Answer №1

Make sure to retrieve the value stored in res

function fetchPalette() {
  return paletteRequest().then(function(response) {
     console.log('fetchPalette', response)
     return response; // Remember to grab the response here
  };
}

Answer №2

Make sure to include the return statement within your first then.

function retrieveData() {
  return dataPromise().then(function(result) {
     console.log('retrieveData', result)
     // process the result

     return result; //<---
  };
}

The .then method itself returns a promise. If the callback function you provide to it returns a non-promise value, that promise will be resolved immediately with that value (which is what happens in this instance where the function returned undefined). Remember, you can also return a promise within your then callback to have the then promise chain to that new promise.

Answer №3

Ensure to include return res statement within the getColors function, check out the example on this plunkr

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

Is there a way to define the width of an element within the display:flex property in CSS?

Could you please review the following: https://codepen.io/sir-j/pen/dyRVrPb I am encountering an issue where setting the input [type=range] to 500px doesn't seem to make a difference from 100px, 500px, or 800px. This leads me to believe that display ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

Two conflicting jQuery plugins are causing issues

In my journey to learn jQuery, I encountered an issue while working on a website that utilizes a scroll function for navigating between pages. The scripts used in this functionality are as follows: <script type="text/javascript" src="js/jquery-1.3.1.mi ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Leveraging jQuery and Ajax for retrieving information from a JSON document

As a newcomer to JS, I have successfully set up a JSON file on my Express server. My code snippet looks like this: const data = require('./src/data.json') app.get('/search', function (req, res) { res.header("Content-Type",'app ...

Updating parameters in Node.js with mongoose

script.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var scriptSchema = new Schema({ status: {type: String, default: 'INCOMPLETE'}, code: String, createdDate: {type: Date, default: Date.now}, user: {t ...

generate code to automatically output the content of a website

I'm in the process of creating a program that automatically navigates to a website and prints a page. Unfortunately, I'm encountering difficulties in getting it to function properly. I've attempted using the selenium chrome driver, but with ...

Trouble with populating Ext.grid.Panel from ExtJS4 JSON data

Despite researching various posts on the topic, I am still facing issues. Even after attempting to create a Panel with minimal data, I cannot seem to make it work. This problem is really puzzling me. Below is the code snippet that I am currently working wi ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

The initialization of an Angular variable through ng-init will consistently result in it being undefined

Currently, I am in the process of learning AngularJS. As part of my learning journey, I decided to initialize a variable using ng-init. However, I encountered an issue where the variable's value always remained undefined. Below is the snippet of code ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

Unusual behavior exhibited by dynamic code in iframe

When trying to retrieve a dynamic height iframe, I implement the code below. In the <head> area <script language="javascript" type="text/javascript"> function adjustIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...

What is the correct way to update an array of objects using setState in React?

I am facing an issue where I have an array of objects that generates Close buttons based on the number of items in it. When I click a Close button, my expectation is that the array should be updated (removed) and the corresponding button element should dis ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

Creating a dynamic div with various paragraphs using only Javascript

My goal is to dynamically generate paragraphs with their respective icons inside individual div elements. For instance, if the service API returns 30 items, I will create 30 div elements with the class "tile". However, if only one item is returned, then I ...

Display various child components in a React application depending on the current state

I'm currently developing a brief React quiz where each question is represented as an independent component. I aim to swap out the current question component with the next one once a question is answered. Here's the present state of my root compon ...

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

Implementing authentication fallback during re-login when a session expires in a web application built with React, Node.js, and Mariadb database

Greetings everyone, this is my debut post here so kindly bear with me :D. Currently, I am in the process of developing a social app where I am incorporating a fallback mechanism for situations when my database goes offline. Within my Login.jsx component, I ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...