What causes an undefined outcome when a promise is fulfilled?

Could you help me understand something?

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    if(true) {
      resolve('success')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(result => console.log(result))

Why do I see 'success' in the console followed by:

Promise {<fulfilled>: undefined}

Why is there undefined when my promise should return a string value of 'success'? Is this due to nested setTimeout? How can I correct this issue?

Answer №1

By making the following adjustments:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    const stat = true;
    if(stat) {
      resolve('success')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(
    result => {console.log('resolve', result); return result;},
    result => {console.log('reject', result); return result;}
)

You will see both the log and the promise return value on your dev tools;

WHY?

Undefined is the result of the implicit return value in the callback (return;). When a function doesn't explicitly return anything, the JavaScript engine will add an implicit return statement to the end of the function body.

Answer №2

@ Mateusz W

When you see the first log 'success' in your console, that is coming from the 'console.log(result)' statement you wrote.

The second log 'Promise {: undefined}' is related to the '

promise1.then(result => console.log(result))
'. This is because the 'then' function itself returns a promise that resolves with the result you pass into it (in this case, you are not returning anything inside then).

To better understand, consider the following code:

promise1.then(result => console.log(result)).then(result1 => {})

This will produce the output:

success
undefined
Promise {<fulfilled>: undefined}

The 'undefined' after 'success' corresponds to what you saw as 'Promise {: undefined}' and represents result1.

It's important not to mix up the

Promise {<fulfilled>: undefined}
you see here (from my code) with the promise1 constant you defined. The former is the result of chaining a second then to your initial then call.

In summary, it might have been confusing thinking that the

Promise {<fulfilled>: undefined}
in your console referred to your promise1. In reality, it indicates the return value of the then function.

Answer №3

It is important to note that the code snippet provided does not show how the data is being retrieved.

Promise {<fulfilled>: undefined}

However, it is possible that the implementation could resemble the following:

promise1.then(result => {
   console.log(result)
   console.log(promise1); // this statement
})

If you were to modify the code as follows:

promise1.then(result => {
   console.log(result)
   console.log(promise1); 
   return result; // updated line
})

The output will change to:

Promise {<fulfilled>: "succes"}

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

jQuery is successfully manipulating pagination on CodeIgniter, however, the link is being updated as well

I've been working on a HTML page called view_closing.php. It includes a table with pagination, and my aim is to ensure that the table can move to another record without refreshing the entire page, all while remaining at the same address: http://localh ...

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...

In what situations should the `#` symbol be used to select a DOM element?

There are times when I have to retrieve elements in the following ways: var object = document.getElementById('ObjectName'); Other times, it's done like this: var object = document.getElementById('#ObjectName'); What distinguishes ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

The wordpress jquery dependency is failing to respond

After converting an HTML ecommerce template into WooCommerce, I am experiencing issues with the functionality. The Nivo slider and some other product features are not working properly. It seems like they are having trouble finding WordPress jQuery, even th ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Starting a fresh SSH terminal directly from a web browser

I have an SSH IP address. Is it feasible to launch an SSH terminal through a web browser, similar to clicking on a hyperlink or Google Play store link? For instance: Click Here to Open SSH Terminal Upon clicking this link, the SSH session should open an ...

Obtain the value from the controller of the amazing-rating component

Currently utilizing the amazing Rating AngularJS library available at https://github.com/bandraszyk/awesome-rating I am interested in understanding how to retrieve the selected value and store it in my controller. The $scope.rating is returning undefined ...

Incorporate an array into a JSON object using AngularJS

I'm attempting to append a JSON array to a JSON object. Here's my code: $scope.packageElement = { "settings": [ { "showNextPallet": true, "isParcelData": false, "isFreightData": true, " ...

Understanding how flex-wrap property works in flexbox is essential for creating

Take a look at the code snippet below: .flex-container { padding: 20px; margin: 20px; list-style: none; border: 1px solid silver; -ms-box-orient: horizontal; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz- ...

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...

Looking to generate an HTML table using JavaScript?

Similar Question: Create HTML table from a Javascript array I have received an array that looks like this var univArray = new Array( {name: "Stanford University", nick: "Stanford", ownership: "private", sys: "n/a", SATh: 1550, SATl: 1360, tui ...

When a specific condition is fulfilled, I must retrieve a random response from a designated array

I'm looking for a way to create a system where users can select multiple items and then generate a random answer from those selected options. Currently, I have a setup that requires manual input of options in a comma-separated format, but I want to st ...

Tips for testing an API that relies on an external library such as "<script src="http://stripe[...]"

Currently, I am working on unit testing an API call to verify it has been executed with the correct properties. The API call is reliant on Stripe's external library that is connected to the window through index.html src="http://stripe[...]". However, ...

nuxt-auth is experiencing difficulties retrieving token information through the refresh provider

I'm currently facing challenges with the login functionality in Nuxt 3. To handle user authentication, I've installed the package @sidebase/nuxt-auth. Below are my configurations set in the file nuxt.config.ts: auth: { globalAppMiddleware: t ...

Displaying content using asynchronous JavaScript and XML (AJAX

I'm currently working on implementing an infinite scroll feature, where more content is loaded as the user reaches the bottom of the page. I am making an ajax call and attempting to render a new view on the backend before sending it back to the fronte ...

What's the reason behind the console showing an uncaught promise error message?

When attempting to delete some lists from my backend using a fetch request, I encountered an issue. The console is displaying an error message that reads "Uncaught (in promise)." What could be causing this problem? Here is the frontend code snippet for th ...

Can you merge multiple req.body requests?

I am exploring a scenario where I have a list of items that need to be iterated through, with each item having the value of i added to it to retrieve the next set of information. For example: By concatenating the string "req.body.item" + i + "Title", you ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Transform every key and value into an array

How can I separate each key and value into individual arrays? Here is the current data: var inputArray = { "3/10/2017": 52, "3/11/2017": 58, "3/12/2017": 70, "3/13/2017": 76 } The desired output should be: var outputArray = [ ["3/10/2017", 52 ...