-2

I'm trying to use a promise in my function but it never returns. This is my code:

function getData(id) {

  return new Promise(function(resolve, reject) {

      DbUtil.connection.query("my query... ", [id],
        function (error, results, fields) {
            if (error) {
              reject(error);
            } else {
              resolve(results);
            }
          }
        );
    }) 
}

The query works and I can see its results in the else block. But the function itself doesn't return. I tried adding a return statement after the resolve, and also after the Promise function itself. But it still doesn't return.

What am I missing?

EDIT: how do I know the function doesn't return? Because

function main() {
    var data = getData(1);
    console.log("data returned? " + data); 
}

in the above main function the log statement is never called.

Eddy
  • 3,533
  • 13
  • 59
  • 89
  • 2
    "But the function itself doesn't return." — What makes you think that? You need to provide a [mcve]. In your provided code, you never call `getData`, let alone do anything to examine its return value. – Quentin Aug 21 '18 at 08:14
  • @Quentin I edited the question as per your comment. – Eddy Aug 21 '18 at 08:19
  • `getData` returns *a Promise*. You need to do `getData().then(data => ...)`. – deceze Aug 21 '18 at 08:19
  • 2
    "the log statement is never called" — The only way that would happen would be if (a) You never call `main()` or (b) there is an exception, in which case there would be an error message. – Quentin Aug 21 '18 at 08:20

1 Answers1

1

It's not the proper way to handle a promise

Try this:

var data;
getData(1).then(function(d) {
  console.log(d);
  data = d;
});
// Since a Promise is async, you can't log data here 

or

async function main() {
  var data = await getData(1);
  console.log(data);
}

Note that this examples does not handle catch case.

Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50