There is a function. The node.js server should return the result of the sql query, but because of the asynchronous nature of js, I can't get the result back because the base doesn't have time to work. Before that, I worked with synchronous languages.

function getCollections() { res = 0; var conn = new sql.Connection(dbConfig); conn.connect().then(function (recordset) { var req = new sql.Request(conn); req.query("SELECT * FROM Collections").then(function (recordset) { conn.close(); res = recordset; }) .catch(function (err) { console.log(err); conn.close(); }) }) .catch(function (err) { console.log(err); }); while (res === 0) { console.log(1);} } app.get("/", function (request, response) { var res = getCollections(); response.send(res); }); 

Reported as a duplicate at Grundy. javascript Feb 22 '17 at 7:45 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    Your database library allows you to write promise- like code. So why not just return the Promise from getCollections ?

    For example, like this:

     function getCollections() { var conn = new sql.Connection(dbConfig); return conn.connect().then(function (recordset) { var req = new sql.Request(conn); return req.query("SELECT * FROM Collections").then(function (recordset) { conn.close(); return Promise.resolve(recordset); }).catch(function (err) { conn.close(); return Promise.reject(err); }); }); } 

    Then the request processing function could be:

     app.get("/", function (request, response) { getCollections().then(function (records) { response.json(records); }).catch(function (error) { response.status(500).json({error: error.toString()}); }); }); 
    • Thanks, the code has become clearer! - Lada

    Drop response.send (res); in getCollections. For example:

     getCollections(request, response); 

    and in `req.query (" SELECT * FROM Collections "). then (function (recordset)

      conn.close(); res = recordset; response.send(res); 

    and in catch's 400

     response.statusCode = 400; response.setHeader('Content-Type', 'application/json'); response.send(JSON.stringify({status:'error', message: 'some error'})); 
    • thanks It works!!! - Lada
    • By getCollection request and response to getCollection you thereby place extra responsibility on this function and increase the coupling. - Dmitriy Simushev