0

I need help to make this promise working.

I just want to call a function and pass a pseudo param and return the results.

Actually it returns undefined

function maFonctionAsynchrone(pseudo) {

    var promise1 = new Promise(function(resolve, reject) {
            connection.query("SELECT * FROM users WHERE MATCH (username) AGAINST ('" + pseudo + "')", function (error, results, fields) {
                if (!!error) {
                    console.log('erreur');
                    reject(error)
                } else {
                    resolve(results)
                    return results
                }
            });
    });
}



app.post('/sendnewpost', function(req, res){
    console.log(maFonctionAsynchrone('pseudotest'))
});
Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35
Ke Vin
  • 77
  • 1
  • 9

1 Answers1

2

Your not returning the promise object from the maFonctionAsynchrone function.

Use return new Promise(function(resolve, reject) within the async function.

Once you return the promise you can assign a then or a catch block to get the result once the promise is resolved asynchronously.

Check the code below

function maFonctionAsynchrone(pseudo) {

    return new Promise(function(resolve, reject) {
            connection.query("SELECT * FROM users WHERE MATCH (username) AGAINST ('" + pseudo + "')", function (error, results, fields) {
                if (!!error) {
                    console.log('erreur');
                    reject(error)
                } else {
                    resolve(results)
                    return results
                }
            });
    });
}

app.post('/sendnewpost', function(req, res){
   maFonctionAsynchrone('pseudotest').then(function(result){
      console.log(result);
   }).catch(function(error){
      console.log(error);
   });
});

Check this link for more examples

  • Oh my god, I tried a similar thing like this and it didn't work... now it works.. Thank you so much – Ke Vin May 13 '18 at 14:20