How to get value from a function that is within the other JS function

Asked

Viewed 30 times

-1

I got a problem. I have the following code with the proper credentials and I can’t return the value that returns in . then(result), I need to make it return a JSON in this function with all the lines, I’ve tried everything and nothing worked Could someone help me? I’m already a good trying to hit head with this. Follows the code

@EDIT--------------------------------------------------------------------------------------------------------------------------------------- Function result in ibm cloud returns so, no errors and no lines to show..

Activation ID: .... Results: {} Logs: []

const sql = require('mssql');

function main(params) {
    var results;
    const config = {
        user: '',
        password: '',
        server: '',
        database: '',
        options: {
            "enableArithAbort": true
        },
    }
    sql.on('error', err => {
        console.log(err)
    })

     sql.connect(config).then(() => {
        return sql.query('SELECT * FROM TABLETESTE')
    }).then(result => {
         results = result.recordset;
        console.dir(result.recordset[0])
    }).catch(err => {
        console.dir(err)
    })
     return JSON.stringify(results); //<--
};
exports.main = main;

1 answer

0


Initially reserve a minute of your time to read about Javascript Promises will help you a lot.

There are a few ways to solve your problem, but the simplest and most beautiful would be to put everything inside the block try/catch and eliminate callbacks, for example:

// Adicione a keyword "async" a sua função para indicar que a mesma retorna uma Promise
async function main(params) {
    const config = {
        user: '',
        password: '',
        server: '',
        database: '',
        options: {
            "enableArithAbort": true
        },
    }
    sql.on('error', console.log);
    
    try {
      // Dentro a função async, você pode usar a keyword "await" para esperar determinado resultado antes de proseguir com o código, se algo der errado ele vai direto para o bloco catch
      await sql.connect(config);
      const result =  await sql.query('SELECT * FROM TABLETESTE');
      
      console.log(result);
      return result.recordset;
      
    }catch(err){
      console.error(err)
    }
};

Browser other questions tagged

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