Query return in Javascript variable

Asked

Viewed 1,432 times

3

I am making a code in Node.js that accesses SQL Server database. I created a variable that stores the result of a query, the problem is that I can’t access this variable outside of the connection method to the database. Follows the code:

var lexml = 'xml';

sql.connect(config).then(() => {
  return sql.query`SELECT ISNULL(CONVERT(VARCHAR(MAX), 
  CONVERT(VARBINARY(MAX), 
  XML_SIG)),'') AS XML_NF  FROM SPED050
WHERE DOC_ID = 36220; `;
}).then(result => {
  lexml = result.recordset[0].XML_NF.toString();
  console.log(lexml); // <---------------Aqui é apresentado o xml normalmente
  return lexml;
}).catch(err => {
    console.dir('Erro na consulta');
})
sql.on('error', err => {
   console.dir('Erro ao acessar o banco'); 
});

console.log(lexml); // <------ Aqui é impresso apenas "xml"

Could someone help me? how can I access the "lexml" variable with the query result outside the connection method?

2 answers

4

That one sql.query returns a promise that in its callback makes available result.

Just the moment that callback is that you have access to the variable, and therefore all the code that needs it has to be called from within that callback.

If for example you have a function next that needs that value you have to call from inside that callback, so:

sql.connect(config).then(() => {
  return sql.query `
      SELECT ISNULL(CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), XML_SIG)),'') AS XML_NF
      FROM SPED050
      WHERE DOC_ID = 36220;
  `;
}).then(result => {
  const lexml = result.recordset[0].XML_NF.toString();
  next(lexml); // <--------------- aqui dás continuação ao fluxo do programa
}).catch(err => {
  console.dir('Erro na consulta');
})
sql.on('error', err => {
  console.dir('Erro ao acessar o banco');
});

2


This is because Node.js is asynchronous, so it does not wait for the result between one instruction and another (in case of asynchronous methods). What you can do is when you fall in callback call a function to give continuity, something like that:

[...]
.then(result => {
  lexml = result.recordset[0].XML_NF.toString();
  exibirXml(lexml)
})
[...]
function exibirXml(xml){
  console.log(xml);
}
  • I got it. I gave it right, thank you very much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.