Query return in Javascript variable

2

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 not access this variable outside the connection method to the database. Here is 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"

Can anyone help me? how can I access the variable "lexml" with the query result outside of the connection method?

    
asked by anonymous 09.06.2017 / 20:57

2 answers

1

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

[...]
.then(result => {
  lexml = result.recordset[0].XML_NF.toString();
  exibirXml(lexml)
})
[...]
function exibirXml(xml){
  console.log(xml);
}
    
09.06.2017 / 21:02
1

This sql.query returns a promise that in your callback makes result available.

Only when this callback is called you have access to the variable, and therefore all the code that needs it must be called from the inside of this callback .

If for example you have a function next that needs this value you must call from within that callback, like this:

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');
});
    
09.06.2017 / 21:01