Complete a promise using the then() method and return the result

I'm working with a JavaScript code snippet that looks like this:

function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();

Every time I check the value of the test variable, it's always undefined. I suspect that this is because the promises haven't been resolved yet. Is there a way to return a value from a promise?

Answer №1

When a result is returned from a callback function within a then() statement, there's a touch of magic involved. If a value is returned, the subsequent then() function will be triggered with that value. On the other hand, if something resembling a promise is returned, the following then() function will pause until that promise is resolved or rejected.

Source: https://web.dev/promises/#queuing-asynchronous-actions

Answer №2

If you want to utilize a promise, you'll need to either invoke a function that generates a promise or craft one yourself. It's important to understand the underlying issue you're attempting to address, but here's an example of how you can create a promise on your own:

function customPromiseExample(input) {
    return new Promise(function(resolve, reject) {
        // perform some asynchronous operation here
        setTimeout(function() {
           // fulfill the promise with a certain value
           resolve(input + 10);
        }, 500);
    });
}

customPromiseExample(29).then(function(value) {
   // retrieve the value from the promise here
   log(value);
});

// output displayed within the snippet
function log(x) {
    document.write(x);
}

Alternatively, if you already have a function that yields a promise, you can leverage that function and return its promise:

// function that yields a promise
function delayTimer(t) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, t);
  });
}

function customPromiseExample(input) {
  return delayTimer(100).then(function() {
    return input + 10;
  });
}

customPromiseExample(29).then(function(value) {
  // retrieve the value from the promise here
  log(value);
});

// output displayed within the snippet
function log(x) {
    document.write(x);
}

Answer №3

In this code snippet, I have made some changes to the justTesting function to ensure that a promise is returned. This allows you to process the result once the function is resolved.

// updated answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // perform actions with the output here :)
  })
  .catch(err => {
    console.log(err);
  });

I hope this explanation is useful!

// previous answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // perform actions with the output here :)
    }

Answer №4

To eliminate confusion with promises, my preference lies in utilizing the "await" command and async functions.

For this scenario, I would establish an asynchronous function initially, which will replace the anonymous function invoked within the "promise.then" section of this query:

async function SubFunction(output){

   // Request made to database, resulting in a promise, similar to an Ajax call:

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Response:
   return response;

}

Subsequently, I would invoke this function within the main function:

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

Note that both the main function and sub function have been transformed into async functions in this context.

Answer №5

In my understanding, the primary goal of the author is to retrieve a value directly from a promise without the need to return another promise. As far as my knowledge goes, achieving this without using a then() or async/await environment seems to be unattainable. It appears that a promise will always be returned regardless of the circumstances.

Answer №6

When using Promises, values are not technically "returned"; instead, they are passed to a callback function specified by using .then().

The concept being communicated is likely that you should include resolve(someData); within the promise implementation.

Then, in the code following the then method, you can access the data stored in someData to perform additional operations.

Answer №7

To effectively solve this problem, utilizing reference data types such as arrays or objects is necessary.

function bar(x, y){
  let output = [];
  const userCategories = new Promise((resolve, reject) => {
                        resolve(['category A', 'category C']);
                      })
  
  userCategories.then((uc) => {
    return new Promise((resolve, reject) => {
      resolve([...uc, 'category D', 'category E']);
    })
  }).then(response => {
    return output.push(...response);
  });
  return output;
};
bar();

Answer №8

When a promise is resolved, you should not try to return a value directly. Instead, you can call a separate function to handle the resolved promise value:

function handlePromise() {
    promise.then(function(data) {
        // Call another function to handle the resolved value
        processValue(data + 1);
    });
}

function processValue(value) {
    // Perform actions with the resolved value
}

var result = handlePromise();

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

Ways to adjust the brightness of any color when hovered over

Is it possible to create a universal effect where an element becomes darker or lighter when hovered over, regardless of the initial color? Here is an example: .change-color{ Background:green; width:100px; height:100px } .change-color:hover{ Background ...

Preparing the format/serialization of a JQuery JSON array prior to submitting it

Looking at the JSON structure I have: { "firstArrayOfJSON": [ { "something" : "something" }, { "another" : "another" }, { "secondArrayOfJson" : [ ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

Handling routerLink exceptions in Angular 2, 4, and 5

In my app, I am working on catching routing exceptions. There are three ways in which a user can navigate: If the user types the address directly - this can be caught easily by using { path: '**', redirectTo: 'errorPage'} in the route ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Issue with React.js button functionality not functioning as expected

import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { items: [] } } addItem(e) { var itemArray = this.state.items; ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Exploring the Issue of Flickering in 3D Models with Three.js and Potree

Currently, I am working with a gltf model from this link: using Three.js and Potree. However, I am facing an issue with the model flickering. I have gone through similar posts on this topic like Flickering planes and Texture/model flickering in distance ( ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Hmm, I seem to be encountering an error where res.sendStatus is not recognized as a function. What could be causing this

For the last few months, I have been immersed in Node.js/Express to create a REST Api. However, I've hit a roadblock with an async function in my controller.js file. The callback function is successfully receiving the client's request, but when i ...

"Integrating auto-expandable rows and subrows into a React table with the use

Presented here is my code for a React table using hooks. I encountered a challenge when trying to set all rows and subrows to be expanded by default upon opening the page. Despite attempting various solutions, none of them proved successful. Check out the ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

What could be causing the inability to move down on this page?

Trying to scroll down a page using Selenium with Python and the execute_script command, but encountering issues. Despite executing the code provided below, I am unable to reach the bottom of the page: def create_browser(first_page=None): print "Starti ...

Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should beco ...

Despite my usage of className, I still encounter the error message "Error: Invalid DOM property `class`."

I am having trouble debugging this issue as I am unsure of the exact location of the error. Here is the link to the repository: https://github.com/kstaver/React-Portfolio Error #2. There are three more promise rejection errors present, which I will addres ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

How can one change the color of movable tiles to red while keeping the rest of the tiles in their original state in a puzzle game?

In this section of our code, the function moveTile is responsible for moving a tile. How can I modify it so that the hover color changes to red? function moveTile(identity) { var emptyId = findEmptySpace(); if (isEmptyNeighbor(identity)) { document.ge ...