How can we map a promise that resolves to foo to a new promise that resolves to bar?

I am working on a function that uses an XMLHttpRequest to retrieve data and returns a promise with the response.

But now I want to modify it so that the promise only contains a specific string from the response.

Instead of resolving to response = {status, data}, I want the promise to return just response.data.some_field

Is there a way to achieve this?

Answer №1

When you chain the .then method to a promise, you are essentially creating a new promise that will resolve to the value returned in the callback function. To implement this, simply add the following code snippet to your current promise:

.then((res) => {
  return res.data.some_value;
});

Your final function may look like this:

function fetchData() {
   return new Promise((resolve, reject) => {
     //performing some action
   }).then((res) => {
      return res.data.some_value;
   });
}

Answer №2

If you're searching for a way to efficiently handle asynchronous operations in JavaScript, then what you need is promise chaining. Check out Mozilla's documentation on promise chaining for more details.

function sendHttpRequestAsync () {
    // This function returns a promise that handles the XMLHttpRequest
}

function fetchDataAsync() {

   // Make an HTTP request, chain the return promise, 
   // and resolve it to retrieve the desired data field.
   return sendHttpRequestAsync() //Utilizing .then() method for promise chaining
       .then((response) => { 
          return response.data.some_field;
       });
}

function executeBusinessLogicFunction () {

     let result = "";

     fetchDataAsync()
         .then((response) => {
              result = response; // Assigning the response to the 'result' variable
          }) 
          .catch(() => {
               console.log("An error occurred or this explanation might not be helpful at all!");
          }); 
     }) 
}


// Alternatively, using async/await for experimentation

async function executeBusinessLogicFunction2 () {

     let result = "";

     try {
         result = await fetchDataAsync();
     } catch (e) {
         console.log("An error occurred or this explanation might not be helpful at all!");
     }
}

In my illustration, I separated the HTTP request into one function and introduced another function that calls the former and executes the promise chaining process. You could simplify the code by excluding the second function and directly returning the chained promise from the initial function handling the HTTP request.

Answer №3

Upon reviewing the code block before you made edits to the question, it appears that you have something like this:

 const promise = axios
    .post(url("fistbump"), data)
    .then(result => {
      window.console.log("Got fistbump response: ", result.data);
      localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
    });

  return promise;

If the Axios promise follows the ES6 promise spec, you can simply modify the .then clause to return the desired value wrapped in a promise, resulting in:

 const promise = axios
    .post(url("fistbump"), data)
    .then(result => {
      window.console.log("Got fistbump response: ", result.data);
      localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
      return result.data;
    });

  return promise;

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

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

Struggling with your Dropdown Menu onclick functionality in Javascript? Let me lend

I am seeking assistance with implementing a Javascript onclick Dropdown Menu. The current issue I am facing is that when one menu is opened and another menu is clicked, the previous menu remains open. My desired solution is to have the previously open menu ...

The Next.js application is functioning smoothly in development, but encounters errors during the building and deployment processes

While my Next.js app compiles and runs smoothly locally during development (using npm run dev), I encounter a failed build when attempting to compile the project (using npm run build). After researching online, it seems that unhandled promises may be the c ...

What is the process for calling an API once and retrieving various content from the same API when using Vuejs?

As a beginner in Vuejs, I am currently working on fetching content from different APIs with similar endpoints but varying IDs. This is the approach I have taken: <template> <div class="body"> <div class="First content&q ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

What is the optimal strategy for managing multilingual text in a React website?

As I develop a react website with multiple localizations, I am faced with the question of how to best store UI texts for different languages. Currently, I am contemplating two approaches: One option is to store text directly in the UI code, using an objec ...

What is preventing my video from filling the entire screen?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=d ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Ensuring that the desired DOM elements have loaded before attempting to manipulate them in Vue.js

I've been struggling with this issue for the past day and I'm completely stuck. In my vue file, there's a method that operates like this: methods: { showSlides(n) { let slides = document.getElementsByClassName("mySlides"); ...

Interactive Div that Adapts

Hello everyone, I'm new to this forum and seeking some assistance. I have a requirement where multiple div contents need to fade in and out dynamically. I found this jsfiddle example that works for 2 divs, but I want it to work for more, say 5 differ ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

Using Javascript to perform redirects within a Rails application

Currently working on a Facebook application using Rails. There are certain pages that require users to be logged in, otherwise they will be directed to a "login" page. I am unable to use redirect_to for this purpose as the redirection must be done through ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...

Error: No route found at this location

I've been following a tutorial on integrating Evernote with IBM's DOORS Next Generation and I added the code highlighted below. // app.js app.get("/notebooks", function(req, res) { var client = new Evernote.Client({ token: req.session.oauth ...

Modify the tooltip of the selected item in an ng-repeat loop in AngularJS

Upon clicking an element, a function is executed which, upon successful completion, should change the tooltip of that specific element. Within an ngRepeat loop, I have multiple elements displaying the same tooltip. However, I only want to update the toolt ...

Is there a way to stream audio directly from a URL on the client-side using ASP.NET?

I am currently working on a web page for an ASP.NET application using .NET Framework Version 4.0 and ASP.NET Version 4.7. My goal is to incorporate audio playback from a server. The specific URL I am dealing with is as follows: . However, I am struggli ...

Confirm before closing the window

How can I get this code to function properly and show a confirmation alert after the user clicks on a button? This is essentially an "exit website button". The confirmation pop-up will have: If "OK" is clicked > the current window will close; If ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...