Categories
JavaScript Answers

How to properly return multiple values from a promise with JavaScript?

Spread the love

Sometimes, we want to properly return multiple values from a promise with JavaScript.

In this article, we’ll look at how to properly return multiple values from a promise with JavaScript.

How to properly return multiple values from a promise with JavaScript?

To properly return multiple values from a promise with JavaScript, we can return a promise that resolves to an array.

For instance, we write

const step1 = () => {
  const server = "myserver.com";
  const data = "so much data";
  return Promise.resolve([server, data]);
};

const f = async () => {
  const [server, data] = await step1();
  //...
};

to create the step1 function.

In it, we call Promise.resolve to create a promise that resolves to an array of data.

Then in function f, we use await to get the resolve value from the promise returned by step1.

And then we destructure the values from the array.

Conclusion

To properly return multiple values from a promise with JavaScript, we can return a promise that resolves to an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *