Achieving resolution of promised information

Upon reviewing the code snippet provided, it can be seen that:

function one(){
    var prm = new Promise(function(resolve,reject){
        resolve("one");
    });
    prm.customKey = function(){
    }
    return prm;
}
function two(){
    var prm = one();
    prm.then(function(res){
        return "two";
    });
    return prm;
}
function three(){
    return one().then(function(res){
        return "two";
    });
}

The expectation was for both cases below to output "two":

However, oddly enough: i) displays "one" in the console, ii) displays "two" in the console.

i) two().then(function(res){
       console.log(res);
   });

ii) three().then(function(res){
       console.log(res);
    });

If anyone could shed light on why this behavior is occurring, it would be greatly appreciated.

Answer №1

When you return prm, it's a commitment that is fulfilled. This represents a commitment that results in return. The point at which you send back "two," the return statement applies to the function within which it's invoked, specifically the callback inside the .then statement.

This action does not impact the promise itself. You merely utilized a promise (from one()) within your two() function and sent it back unaltered.

Answer №2

When implementing the second and third functions, it is important to include a new Promise that will wait for other Promises to resolve before proceeding. Here's an example:

function three(){
   return new Promise((resolve,reject) => {
      two().then(() => resolve("three"));
   });
}

Answer №3

When looking at the function two, we can see that the prm variable does not actually get updated when it is returned by the function.

Right after the line: var prm = one();

the code moves directly to: return prm;

This happens because the function is not set up to receive data from the promise at that moment.

However, in contrast, in the function three, the promise is returned, resulting in the expected outcome.

To make sure that function two yields the same results as function three, you need to include async and await in the code:

async function two(){
    var prm = one();
    await prm.then(function(res){
        prm = "two";
    });
    return prm;
}

Answer №4

Consider updating the function as shown below:

function updateFunction(){
  var prm = originalFunction();
  prm.then(function(response){
    return "updated";
 });
}

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 Ajax script is malfunctioning

Currently, I have a program that requires the user to input a city and country. The program then checks the database to see if the city already exists - displaying a warning message using ajax if it does, or adding the city to the database if it doesn&apos ...

Provide arguments for Auth0 registration

Incorporating Auth0's provided login and sign-up screen (check it out at https://auth0.com/docs/quickstart/webapp/nextjs/01-login#add-login-to-your-application) into my application has been a seamless process. Upon signup, I have implemented a callbac ...

Displaying default tab content while hiding other tab content in Javascript can be achieved through a simple code implementation

I have designed tabs using the <button> element and enclosed the tab content within separate <div></div> tags like shown below: function displayTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsB ...

When setting properties on the Object or Array prototype in JavaScript, it disrupts the functionality of brackets

Similar Question: Adding functions to the Array class in JavaScript causing issues with for loops While it may not be best practice, I want all objects to have this specific function when including a certain piece of code. I find it strange that when ...

Deleting a database row when the cancel button is pressed

I have a scenario where I need to remove a database row containing a file name when the user clicks on the cancel button. However, despite my efforts, the database row is not being deleted. Can anyone help me identify what I might be doing wrong? Here is ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

Secure your password with Vue JS encryption techniques

I am looking for a way to safely encrypt passwords on my Vue JS web application. While I already have a hash encrypter set up on the API, I am running into an issue where the password is displayed as plain text during the signin or signup call. Any recom ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

Utilizing the .fadeToggle() function to create a fading effect for text, which fades in and out

I am on the verge of achieving my goal, but I could use a little more assistance with this. $('.change').hover(function() { $(this).fadeToggle('slow', 'linear', function() { $(this).text('wanna be CodeNinja' ...

Apache conf file configured with CSP not functioning properly when serving PHP files

While configuring the Apache CSP lockdown for a site, I encountered an unusual behavior when opening the same file as a PHP script compared to opening it as an HTML file. The HTML file looks like this: <html> <head> <meta http-equiv= ...

Adjust the header as the user scrolls

Having a little issue with my header. I'm new to Bootstrap and would like to change my header when scrolling down. Everything works perfectly, but when I reload the page, the header remains in the "scrolling state". Apologies for any language mistakes ...

How to implement jquery select functionality on clickable table rows?

I've come across a challenge while trying to implement clickable table rows with the jquery selectable function. Everything works perfectly fine with li elements, but I seem to hit a roadblock when using tables - the click event just stops working. Wh ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

Issue with MERN stack: User not being saved in mongoDB despite lack of errors

Check out the repository at https://github.com/QexleLLC/Otlic After running the frontend with npm start, and starting the backend with nodemon server, everything appeared to be working fine. However, when I tried signing up by going to localhost:3000/sign ...

Enable the button when there is an error after submission in AngularJS

Has anyone encountered issues with dynamically disabling a button? I noticed that my API delays for 2 seconds to mimic a slow connection. I expected the submit button to be disabled upon submission and then re-enable itself. In HTML, manually disabling t ...

Choosing an element from a multiple group listbox with jQuery

Is there a way to select items in the listbox using jQuery when dealing with optgroup elements? $('#id option[value=<?php echo $row; ?>]').attr('selected','selected'); The above code works for regular options, but how ...

Transforming user-entered date/time information across timezones into a UTC timezone using Moment JS

When working on my Node.js application, I encounter a scenario where a user inputs a date, time, and timezone separately. To ensure the date is saved without any offset adjustments (making it timezone-independent), I am utilizing Moment Timezone library. ...

Upon submitting the form, the dynamic dependent drop-down list fails to offer any available options

Hey there, I've got a form with two drop-down lists: id="dd-1" & id="dd-2". The options in id="dd-2" are generated from the database based on what's selected in id="dd-1"; I'm using onChange=getChildOf(this.value) in id="dd-1" for this ...