Created
July 27, 2018 00:20
-
-
Save rhlsthrm/a9ac955d7298783b09404b94abcd0c42 to your computer and use it in GitHub Desktop.
Example of creating and awaiting Promise in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// return a promise so you can await it | |
function Insert_Machine(msg, callback) { | |
var result = []; | |
var connection = new Connection(machine_config); | |
return new Promise(function(resolve, reject) { | |
connection.on("connect", function(err) { | |
var request = new Request( // set up request structure | |
"INSERT INTO dbo.Data_new (pp_id, d_No, d_Note, d_Data, d_seq, d_machine, d_DateTime) OUTPUT INSERTED.Id VALUES (@pp_id, @d_No, @d_Note, @d_Data, 0, @d_machine, @d_DateTime);", | |
function(err, rowCount) { | |
if (err) { | |
reject(err); // print error on console if anything happens | |
} else { | |
console.log(rowCount + " rows inserted to Machine_Data: " + msg); // confirm the insert | |
} | |
resolve(result); // resolve promise | |
} | |
); | |
request.on("row", function(columns) { | |
result.push(columns); | |
}); | |
request.addParameter("pp_id", TYPES.NVarChar, msg[0]); | |
request.addParameter("d_No", TYPES.NVarChar, msg[1]); | |
request.addParameter("d_Note", TYPES.NVarChar, msg[2]); | |
request.addParameter("d_Data", TYPES.NVarChar, msg[3]); | |
request.addParameter("d_machine", TYPES.NVarChar, msg[4]); | |
request.addParameter("d_DateTime", TYPES.NVarChar, msg[5]); | |
// Execute SQL statement | |
connection.execSql(request); | |
}); | |
}); | |
} | |
async function parse_message(data, m_id, type) { | |
//console.log('Message received = ' + data); | |
var msg = data.toString("utf8"); // Convert from object class, split CRs | |
var strings = msg.split("\r\n"); // split multi-line data | |
console.log("Strings: " + strings); | |
for (const element of strings) { | |
var payload = element.split("///"); // split by separator | |
if (payload.length == 4) { | |
// If array is properly formed | |
payload[3] = payload[3].trim(); | |
if (payload[3].includes("N")) { | |
payload[3] = payload[3].slice(1, payload[3].length); | |
} | |
payload[4] = m_id; // Send machine ID | |
payload[5] = dt.getDateTime(); | |
// await the promise so that | |
if (type == "Machine") { | |
await Insert_Machine(payload); | |
} else if (type == "Pallet") { | |
await Insert_Pallet(payload); | |
} else { | |
console.log( | |
"Type didn't come through. Where am I supposed to put this?" | |
); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment