1

I will try be simple, when I want to execute a query async in a function (SetLogs), I will see in my logs my console.log('query 1 log') at the end of all my call, instead to see him between console.log('start log '); and console.log('return pool logs'); I have 2 parts :

My main call

logs.SetLogs(pool, req, res).then(bResultLog=> {
    console.log('return pool logs');
})

console.log("END")
return pool

SetLogs Function :

static async SetLogs(pool, req, res) {
  
    var now = new Date();
    var endpoint = req.originalUrl.split("?")[0].replace("/", "")

    var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
    
    console.log('start log ');
    
    pool.query(query, function(err, results) {
        console.log('query 1 log ');
        return true
    });
    
    console.log('fin log ');

}

This is my logs :

start log
fin log
END
return pool logs
query 1 log
Jonathan Delean
  • 1,011
  • 1
  • 8
  • 25
  • 1
    you are missing `await` – Crocsx Aug 05 '21 at 14:12
  • 4
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Yannick K Aug 05 '21 at 14:13
  • I dont use mysql promsie, the callback function should do the async – Jonathan Delean Aug 05 '21 at 14:15
  • 1
    See [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) to convert your callback to a promise – Reyno Aug 05 '21 at 14:16

1 Answers1

0

As I said above, you are missing await, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

async function SetLogs() {
 
    var now = new Date();
    console.log('start log');
    
    var res = await queryTest();
    console.log(res);
    console.log('fin log');
}

function queryTest() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('foo');
    }, 300);
  });
}

SetLogs();
Crocsx
  • 2,534
  • 1
  • 28
  • 50