0

I have the following function and I want it to return the variable recordset, or more accurately I want to be able to access that info from the code that calls the getData() function. How can I do this?

function getData() {
    sql.connect("mssql://username:password@localhost/mytestdatabase").then(function () {
        return new sql.Request().query('select * from _table')
            .then(function (recordset) {
                console.log(recordset); // <-- THIS IS WHAT I WANT TO RETURN
            })
            .catch(function (err) {
                console.log("Query Error: " + err);
            })
    }).catch(function (err) {
        console.log("Connection Error: " + err);
    })
};
George Edwards
  • 8,979
  • 20
  • 78
  • 161
  • You can't do that. You need to use more promises (or rather, return the promise). – SLaks Jul 18 '16 at 17:42
  • you need to return the connect(), which should give you a promise you can consume downstream. – dandavis Jul 18 '16 at 17:42
  • Also, your error handling is wrong. You should leave errors so that the caller can handle them. Read http://blog.slaks.net/2015-06-10/advanced-promise-usage/ – SLaks Jul 18 '16 at 17:42
  • *"I have the following function and I want it to return the variable `recordset`"* You can't. *"or more accurately I want to be able to access that info from the code that calls the `getData()` function."* Have it return a promise, and have that code consume the promise. – T.J. Crowder Jul 18 '16 at 17:44
  • literally, just prepend `return ` to the function body to be able to `getData().then()` anywhere... – dandavis Jul 18 '16 at 17:48
  • @dandavis OK, so if I do that and am returning the `sql.connect()`, what would my `.then(` look like to access the `recordset`? – George Edwards Jul 18 '16 at 17:50
  • you can just wrap a one-parameter anon around the code following the call, where the data is needed; the recordset (or something to get at it) should be that first (and only) argument. – dandavis Jul 18 '16 at 17:52
  • @dandavis could you post an e.g. ? I'm not quite sure how that would work, and I'd like to mark something as the answer. – George Edwards Jul 18 '16 at 18:02
  • `var x=a(); b(x);` becomes `a().then(b)`, this question is dead now... – dandavis Jul 18 '16 at 18:07

0 Answers0