javascript - Return from a promise then()

hljs.highlightAll();

Javascript - Return from a Promise then()

If you are working with promises in Javascript, you will most likely come across the .then() method. This method is used to handle the result of a promise after it has been resolved. However, it is essential to understand how to return a value from a .then() callback function.

Using a return statement in .then()

The simplest way to return a value from a .then() callback function is by using the return statement. Here is an example:

// Promise
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Resolved!');
  }, 1000);
});

// .then() callback function
promise.then((result) => {
  return result.toUpperCase();
}).then((result) => {
  console.log(result);
});

In this example, we create a promise that resolves after 1 second with the value 'Resolved!'. We then use the .then() method to handle the promise result. In the first .then() callback function, we use the return statement to return the uppercase version of the result. We then chain another .then() method to log the final result to the console.

Using Promise.resolve()

Another way to return a value from a .then() callback function is by using the Promise.resolve() method. Here is an example:

// Promise
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Resolved!');
  }, 1000);
});

// .then() callback function
promise.then((result) => {
  return Promise.resolve(result.toUpperCase());
}).then((result) => {
  console.log(result);
});

In this example, we use the Promise.resolve() method to create a new promise that immediately resolves with the uppercase version of the result. We then return this new promise from the .then() callback function. We then chain another .then() method to log the final result to the console.

Conclusion

Returning a value from a .then() callback function is an essential concept to understand when working with promises in Javascript. Both using a return statement and Promise.resolve() are valid ways to achieve this. However, using Promise.resolve() may provide more flexibility in some cases.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe