{"action":"created","issue":{"url":"https://api.github.com/repos/tediousjs/tedious/issues/458","repository_url":"https://api.github.com/repos/tediousjs/tedious","labels_url":"https://api.github.com/repos/tediousjs/tedious/issues/458/labels{/name}","comments_url":"https://api.github.com/repos/tediousjs/tedious/issues/458/comments","events_url":"https://api.github.com/repos/tediousjs/tedious/issues/458/events","html_url":"https://github.com/tediousjs/tedious/issues/458","id":179679942,"number":458,"title":"Requests can only be made in the LoggedIn state, not the SentClientRequest state (code: 'EINVALIDSTATE')","user":{"login":"SaloniSonpal","id":17992339,"avatar_url":"https://avatars2.githubusercontent.com/u/17992339?v=4","gravatar_id":"","url":"https://api.github.com/users/SaloniSonpal","html_url":"https://github.com/SaloniSonpal","followers_url":"https://api.github.com/users/SaloniSonpal/followers","following_url":"https://api.github.com/users/SaloniSonpal/following{/other_user}","gists_url":"https://api.github.com/users/SaloniSonpal/gists{/gist_id}","starred_url":"https://api.github.com/users/SaloniSonpal/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/SaloniSonpal/subscriptions","organizations_url":"https://api.github.com/users/SaloniSonpal/orgs","repos_url":"https://api.github.com/users/SaloniSonpal/repos","events_url":"https://api.github.com/users/SaloniSonpal/events{/privacy}","received_events_url":"https://api.github.com/users/SaloniSonpal/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":14,"created_at":"2016-09-28T04:56:09Z","updated_at":"2018-02-21T20:00:58Z","closed_at":null,"author_association":"NONE","body":"In my example below, I'm trying to serially execute an array of functions. But the Requests can only be made in the LoggedIn state, so I had to check for that `connection.state !== connection.STATE.LOGGED_IN`. And as you can see in the **Read** function below had to put the request back in queue in order to get rid of the error.\n\n``` JavaScript\n{ [RequestError: Requests can only be made in the LoggedIn state, not the SentClientRequest state]\n  message: 'Requests can only be made in the LoggedIn state, not the SentClientRequest state',\n  code: 'EINVALIDSTATE' }\n```\n\nIs there a better way of achieving this?  I see that a similar issues were brought up before [#19](https://github.com/tediousjs/tedious/issues/19) and [#355](https://github.com/tediousjs/tedious/issues/355). Is there a recommended way of executing multiple requests on a connection?\n\nCode:\n\n``` JavaScript\nvar Connection = require('tedious').Connection;  \nvar Request = require('tedious').Request;  \nvar TYPES = require('tedious').TYPES;  \nvar async = require('async');\n\n// Create connection to database\nvar config = {\n        userName: 'mylogin',  \n        password: 'mypassword',  \n        server: 'localhost',\n        options: {\n            // encrypt: true, /*If you are connecting to a Microsoft Azure SQL database, you will need this*/\n            database: 'testdb'\n        }\n    }\nvar connection = new Connection(config);  \n\n// Attempt to connect and execute queries if connection goes through\nconnection.on('connect', function(err) {  \n    if (err) {\n        console.log(err);\n    }  \n    else    {\n        console.log(\"Connected\");\n\n        // Execute all functions in the array serially\n        async.waterfall([\n            function Start(callback){\n                console.log(\"Starting...\");\n                callback(null, 'Jake', 'United States');\n            },\n            function Insert(name, location, callback){\n                console.log(\"Inserting into Table...\");\n\n                request = new Request(\"INSERT dbo.employees (name, location) OUTPUT INSERTED.id VALUES (@Name, @Location);\", function(err){  \n                     if (err) {\n                            console.log(err);\n                        }  \n                    }\n                );  \n                request.addParameter('Name', TYPES.NVarChar, name);  \n                request.addParameter('Location', TYPES.NVarChar, location);  \n\n                request.on('row', function(columns) {  \n                    columns.forEach(function(column) {  \n                      if (column.value === null) {  \n                        console.log('NULL');  \n                      } else {  \n                        console.log(\"Employee id inserted is \" + column.value);  \n                      }  \n                    });  \n                }); \n\n                // Check how many rows were inserted\n                request.on('doneInProc', function(rowCount, more) {  \n                    console.log(rowCount + ' row(s) inserted');  \n                    callback(null, 'Jared');\n                });             \n\n                connection.execSql(request);  \n            },\n            function Read(callback){\n                // Requests can only be made in the LoggedIn state, so check for that\n                if (connection.state !== connection.STATE.LOGGED_IN) {\n                    // Put the request back on the dispatcher if connection is not in LoggedIn state\n                    setTimeout(Read, 0, callback);\n                    return;\n                }\n\n                console.log(\"Reading rows from the Table...\");\n\n                // Create the request to read from table\n                request = new Request(\"SELECT * FROM dbo.employees;\", function(err) {  \n                    if (err) {\n                        console.log(err);\n                    }  \n                });  \n\n                // Output the number of rows read \n                request.on('doneInProc', function (rowCount, more, rows) {  \n                    console.log(rowCount + ' row(s) returned');  \n                    callback(null);\n                });  \n\n                connection.execSql(request);  \n            }],\n            function Complete(err, result) {\n                if(err) {\n                    console.log(\"Error:\", err);\n                }\n                else {\n                    console.log(\"Done!\");\n                }\n            }\n        )\n    }\n});\n```\n"},"comment":{"url":"https://api.github.com/repos/tediousjs/tedious/issues/comments/367452308","html_url":"https://github.com/tediousjs/tedious/issues/458#issuecomment-367452308","issue_url":"https://api.github.com/repos/tediousjs/tedious/issues/458","id":367452308,"user":{"login":"pablobvch","id":8959595,"avatar_url":"https://avatars3.githubusercontent.com/u/8959595?v=4","gravatar_id":"","url":"https://api.github.com/users/pablobvch","html_url":"https://github.com/pablobvch","followers_url":"https://api.github.com/users/pablobvch/followers","following_url":"https://api.github.com/users/pablobvch/following{/other_user}","gists_url":"https://api.github.com/users/pablobvch/gists{/gist_id}","starred_url":"https://api.github.com/users/pablobvch/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/pablobvch/subscriptions","organizations_url":"https://api.github.com/users/pablobvch/orgs","repos_url":"https://api.github.com/users/pablobvch/repos","events_url":"https://api.github.com/users/pablobvch/events{/privacy}","received_events_url":"https://api.github.com/users/pablobvch/received_events","type":"User","site_admin":false},"created_at":"2018-02-21T20:00:58Z","updated_at":"2018-02-21T20:00:58Z","author_association":"NONE","body":"Hey, everyone, I have the same problem.\r\n\r\ndebug:\r\n\r\n> Requests can only be made in the LoggedIn state, not the SentClientRequest state\r\n> (node:5180) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RequestError: Requests can only be made in the LoggedIn state, not the SentClientRequest state\r\n> (node:5180) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\r\n\r\nIs it resolved yet? This is my code.\r\n\r\n```\r\nfunction createAsPromiseWithTransaction(callback, data, connection) {\r\n\r\n  const transactionReady = (err) => {\r\n    if (err) {\r\n      return callback(err)\r\n    }\r\n    return callback(null)\r\n  }\r\n\r\n  const transactionFailed = (originalErr) =>\r\n    (err) => {\r\n      if (err) {\r\n        return callback(err)\r\n      }\r\n      return callback(originalErr)\r\n    }\r\n\r\n  const willIGetArea = new Promise(\r\n    (resolve, reject) => {\r\n      const create = function(data, connection) {\r\n        let areaIdInserted = null\r\n        const request = new Request(CONSTANTS.SPNames.Area,\r\n          (err, rowCount, rows) => err ? reject(err) : resolve(areaIdInserted))\r\n\r\n        request.addParameter('IUser', TYPES.UniqueIdentifier, data.iUser)\r\n        request.addParameter('ParentArea', TYPES.Int, data.parentArea)\r\n        request.addParameter('Name', TYPES.VarChar, data.nameArea)\r\n        request.addParameter('ShortName', TYPES.VarChar, data.shortNameArea)\r\n        request.addParameter('Description', TYPES.VarChar, data.descriptionArea)\r\n        request.addParameter('Gender', TYPES.Bit, data.gender)\r\n        request.addParameter('Colour', TYPES.VarChar, data.colour)\r\n        request.addParameter('X', TYPES.Int, data.x)\r\n        request.addParameter('Y', TYPES.Int, data.y)\r\n        request.addParameter('Active', TYPES.Int, data.active)\r\n\r\n        request.on('row', function(columns) {\r\n          areaIdInserted = columns[1].value\r\n        });\r\n\r\n        connection.callProcedure(request)\r\n      }\r\n\r\n      const transactionStarted = function(err) {\r\n        if (err) return callback(err)\r\n        create(data, connection)\r\n      }\r\n\r\n      connection.beginTransaction(transactionStarted)\r\n    })\r\n\r\n  const willIGetSymptom = function(areaId) {\r\n\r\n    return new Promise(function(resolve, reject) {\r\n\r\n      const create = function(data, connection, areaId) {\r\n        let symptomIdInserted = null\r\n        const request = new Request(CONSTANTS.SPNames.Symptom,\r\n          (err, rowCount, rows) => err ? reject(err) : resolve(symptomIdInserted))\r\n\r\n        request.addParameter('IUser', TYPES.UniqueIdentifier, data.iUser)\r\n        request.addParameter('AreaId', TYPES.BigInt, areaId)\r\n        request.addParameter('Code', TYPES.VarChar, data.code)\r\n        request.addParameter('Name', TYPES.VarChar, data.nameSymptom)\r\n        request.addParameter('ShortName', TYPES.VarChar, data.shortNameSymptom)\r\n        request.addParameter('Description', TYPES.VarChar, data.descriptionSymptom)\r\n        request.addParameter('Gender', TYPES.Bit, data.gender)\r\n        request.addParameter('Active', TYPES.Bit, data.active)\r\n\r\n        request.on('row', function(columns) {\r\n          symptomIdInserted = columns[1].value\r\n        });\r\n\r\n\r\n        connection.callProcedure(request)\r\n      }\r\n\r\n      create(data, connection, areaId)\r\n\r\n    })\r\n  }\r\n\r\n  const willIGetModifier = new Promise(function(resolve, reject) {\r\n\r\n    const request = new Request(\r\n      CONSTANTS.SPNames.Modifier,\r\n      function(err, rowCount, rows) {\r\n        if (err) {\r\n          reject(err)\r\n        } else {\r\n          resolve(rowCount,rows)\r\n        }\r\n      })\r\n\r\n    request.addParameter('IUser', TYPES.UniqueIdentifier, data.iUser)\r\n    request.addParameter('Name', TYPES.VarChar, data.nameModifier)\r\n    request.addParameter('Order', TYPES.SmallInt, data.order)\r\n    request.addParameter('Active', TYPES.Bit, data.active)\r\n\r\n    connection.callProcedure(request)\r\n\r\n  })\r\n\r\n  const runPromise = () =>\r\n    willIGetArea\r\n    .then( (areaId) =>\r\n      willIGetSymptom(areaId)\r\n      .then( (symptomId) =>\r\n        willIGetModifier\r\n        .then((rowCount,rows) => connection.commitTransaction(transactionReady))\r\n        .catch((err) => connection.rollbackTransaction(transactionFailed(err)))\r\n      )\r\n      .catch((err) => connection.rollbackTransaction(transactionFailed(err)))\r\n    )it \r\n    .catch((err) => connection.rollbackTransaction(transactionFailed(err)))\r\n\r\n  runPromise()\r\n\r\n}\r\n\r\n```\r\n\r\nIf I call willIGetArea and willIGetSymptom, all this works but, if I call it with willGetModifier, I have the same problem as well. Thanks a lot."}}
{"actor":{"display_login":"pablobvch"}}