From 09a28729d5199acfe1f47e7a6e76863d57c51b1d Mon Sep 17 00:00:00 2001 From: tonioss22 <45774106+tonioss22@users.noreply.github.com> Date: Tue, 11 Jan 2022 08:11:03 -0500 Subject: [PATCH] Added toObjectAsync and toObjArrayAsync. These functions will not block the event loop compared to the original toObject function. They also return from a promise instead of a callback. These functions are really useful when dealing with big data as return value. Performances are similar to the original method. --- lib/resultset.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/lib/resultset.js b/lib/resultset.js index d175f3f..2d90b28 100644 --- a/lib/resultset.js +++ b/lib/resultset.js @@ -52,6 +52,48 @@ function ResultSet(rs) { })(); } +ResultSet.prototype.toObjArrayAsync = function () { + return new Promise((resolve, reject) => { + this.toObjectAsync().then((results)=> { + resolve(results.rows) + }).catch((err) => reject(err)) + }) +}; + +ResultSet.prototype.toObjectAsync = function () { + return new Promise((resolve, reject) => { + var tick = + (process && process.versions && process.versions.node === '0.9.0') ? + tickShim : + (setImmediate || process && process.nextTick|| tickShim); + + function tickShim(fn) {setTimeout(fn, 1);} + + this.toObjectIter(function (err, rs) { + if (err) reject(new Error(err)); + + var rowIter = rs.rows; + var rows = []; + var row = rowIter.next(); + + (function next() { + // invoke the iterator function + rows.push(row.value); + row = rowIter.next(); + + if (!row.done) { + tick(next); + } + else{ + rs.rows = rows; + resolve(rs); + } + })(); + }); + + }) +} + ResultSet.prototype.toObjArray = function (callback) { this.toObject(function (err, result) { if (err) return callback(err);