How to destructure Javascript/Typescript variables inside of a try/catch block [closed]

Consider that you’re assigning values to variables when using destructuring an object inside of a try/catch block in Javascript. We’ll need these variables later in the function.

Currently, I’m wrapping the entire assignment with parentheses:

async function myFunction() {
  let query, variables;
  try {
    ({ query, variables } = await giveMeVariables()) // Here...
  } catch (err) {
    console.log("An error ocurred");
  }

  console.log("QUERY", query);
  console.log("VARIABLES", variables);
}

function giveMeVariables () {
  return new Promise((resolve, reject) => {
    resolve({ query: "hi", variables: "there" });
  });
}


Looking on MDN: “The parentheses ( … ) around the assignment statement are required when using object literal destructuring assignment without a declaration.” Is this the preferred way of handling try/catch blocks with destructuring, or is there a better approach?

Also, how would you type this in Typescript? Would you have to type the initial variable as undefined/your expected result?

Answer

At the moment you’re not returning anything from myFunction. I would return the data immediately from that function, and await it, and then log it.

function giveMeVariables() {
  return new Promise((resolve, reject) => {
    resolve({ query: "hi", variables: "there" });
  });
}

async function myFunction() {
  try {
    return giveMeVariables();
  } catch (err) {
    console.log("An error ocurred");
  }
}

(async() => {
  const { query, variables } = await myFunction();
  console.log("QUERY", query);
  console.log("VARIABLES", variables);
})();