A
A
amiznikov2021-08-17 18:12:39
JavaScript
amiznikov, 2021-08-17 18:12:39

Why isn't destructuring assignment done without a condition?

Hello everyone, the question is rather just for reasoning and understanding zhs.
There is this code:

async function requestKeyParsingToken() {
  try {
    const { data } = await request({
      method: "get",
      url: TOKEN_SETTINGS,
    })    

    ({public_key: keyParsingTokenEndpoint} = data);    
  } catch (error) {
    console.log(error)
  }
}


request - under the hood of this function, a normal axios request
As I wrote above, the code does not work, but if I set a condition
if(data) {
    ({public_key: keyParsingTokenEndpoint} = data);    
  }

then everything will work.
why so I do not quite understand.
I only have this option: js thinks that data will be empty and gives an error in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-08-17
@amiznikov

In this form, JS perceives the entire structure as a single expression, while the if statement contributes to the automatic placement of semicolons.
The result is the following sequence of actions:

async function requestKeyParsingToken() {
  try {
    ({public_key: keyParsingTokenEndpoint} = data);
    const {data} = await request({
      method: "get",
      url: TOKEN_SETTINGS,
    })(data);     
  } catch (error) {
    console.log(error)
  }
}
And the error occurs due to the use of a variable before its declaration, which is prohibited with variables declared via let and const, this is called "dead float".
PS eslint helps to avoid such errors (as well as many others), specifically in this case, the semi rule with the always parameter would help

P
profesor08, 2021-08-17
@profesor08

const { data } = await request({
      method: "get",
      url: TOKEN_SETTINGS,
    }); // точку с запятой сюда иначе следующие скобки () отработают как вызов функции. Как код отрабатывает справа на лево.

const {public_key: keyParsingTokenEndpoint} = data;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question