You are viewing the preview version of this book
Click here for the full version.

Returning multiple values

As we've discussed in the The Promise constructor chapter, just like normal functions, a Promise can have a single return value. But oftentimes you'll want to return multiple things.

Fortunately, JavaScript supports the object and the array destructuring operators that makes it easy to use a single variable to hold multiple things.

For example, a Promise can resolve with an array of values:

const getValues = () => new Promise((res) => {
  const user = "user";
  const group = "group";
  res([user, group]);
});

const [user, group] = await getValues();
// user, group

Or an object with known fields:

const getValues = () => new Promise((res) => {
  const user = "user";
  const group = "group";
  res({user, group});
});

const {user, group} = await getValues();
// user, group

Of course, it's the same pattern that you'd use for synchronous functions:

const getValues = () => {
  const user = "user";
  const group = "group";
  return {user, group};
};

const {user, group} = getValues();
// user, group

And works the same with async functions too:

const getValues = async () => {
  const user = "user";
  const group = "group";
  return {user, group};
};

const {user, group} = await getValues();
// user, group