I want to ping a few sites using javascript, and found this pen and does what I want.
However, I don't understand when I add goo12121212gle.com to the list of sites as a test it comes up saying that the domain has responded but in the console log I see ERR_NAME_NOT_RESOLVED??
I am new to JS but I am not sure why the below script is both saying the site is there and not at the same time? Is something missing from the script?
function ping(ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('online');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('offline', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
var PingModel = function (servers) {
var self = this;
var myServers = [];
ko.utils.arrayForEach(servers, function (location) {
myServers.push({
name: location,
status: ko.observable('unchecked')
});
});
self.servers = ko.observableArray(myServers);
ko.utils.arrayForEach(self.servers(), function (s) {
s.status('checking');
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
});
};
var komodel = new PingModel(['goo12121212gle.com','msn.com','104.46.36.174','23.97.201.12']);
ko.applyBindings(komodel);
https://codepen.io/lyellick0506/pen/NGJgry
Both the onerror- and onload-callback use "responded" as the message, so there is no way to differentiate between them:
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e); // <--- change this to a different message
}
};
Alternatively you could just check if the e parameter has been set:
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
Related
I am trying to convert this whole section of code from Javascript to GopherJs.
So far i have not been able to do event listeners as i am still a newbie to Javascript.
This is the JavaScript
window.addEventListener("load", function(evt) {
var output = document.getElementById("output");
var input = document.getElementById("input");
var ws;
var print = function(message) {
var d = document.createElement("div");
d.innerHTML = message;
output.appendChild(d);
};
document.getElementById("open").onclick = function(evt) {
if (ws) {
return false;
}
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
print("OPEN");
}
ws.onclose = function(evt) {
print("CLOSE");
ws = null;
}
ws.onmessage = function(evt) {
print("RESPONSE: " + evt.data);
}
ws.onerror = function(evt) {
print("ERROR: " + evt.data);
}
return false;
};
document.getElementById("send").onclick = function(evt) {
if (!ws) {
return false;
}
print("SEND: " + input.value);
ws.send(input.value);
return false;
};
document.getElementById("close").onclick = function(evt) {
if (!ws) {
return false;
}
ws.close();
return false;
};
});
I have gone through a few iterations of attempts but it is still not working.
Below is a snippet of my last attempt.
var ws *websocketjs.WebSocket
var err error
//js.Global.Get("document").Call("write", "Hello world!")
js.Global.Call("addEventListener", "load", func(ev *js.Object) {
//js.Global.Get("document").Get("open") = func(ev *js.Object){
onOpen := func(ev *js.Object) {
if ws == nil {
ws, err = websocketjs.New("ws://localhost:8000/ws") // Does not block.
if err != nil {
println(err)
}
}
fmt.Println("we are past the ws part")
js.Global.Get("document").Call("write", "It is opened!")
/////////////////////////////////////////////////
err = ws.Send("Hello Websockets!") // Send a text frame.
if err != nil {
fmt.Println(err)
}
println("it is open now")
}
ws.AddEventListener("open", false, onOpen)
//}
})
//ws.AddEventListener("open", false, onOpen)
//ws.AddEventListener("message", false, onMessage)
//ws.AddEventListener("close", false, onClose)
//ws.AddEventListener("error", false, onError)
err = ws.Close()
I would atleast like to see the first 2 parts done correctly. I can finish the rest with a good example.
Thanks
To obtain the DOM i used "honnef.co/go/js/dom" library.
Everything else was step by step as in Javascript.
Example:
package main
import "honnef.co/go/js/dom"
func main() {
d := dom.GetWindow().Document()
h := d.GetElementByID("foo")
h.SetInnerHTML("Hello World")
}
I have a custom extended property attached to the window object in JavaScript as follows:
Community.js
(function (window, document, $) {
'use strict';
var containerScrollPositionOnHideList = [];
var scrollToTopOnShowContainerList = [];
var userProfileInfo = {};
window.Community = $.extend({
//init
init: function () {
var Site = window.Site;
Site.run();
this.enableHideShowEventTrigger();
},
setUserInfo: function (userObj) {
if (UtilModule.allowDebug) { debugger; }
window.localStorage.setItem('userInfo', JSON.stringify(userObj));
var d = new $.Deferred();
$.when(this.initUserProfile(userObj.UserId)).done(function () {
d.resolve("ok");
});
},
getUserInfo: function () {
var userJson = window.localStorage.getItem('userInfo');
var userObj = JSON.parse(userJson);
return userObj;
},
})(window, document, jQuery);
The problem is that this extension property window.Community is null in certian scenarios when i refresh the page which i am going to describe below along with flow of code.
and here is a module in JavaScript to force reload scripts even if they are cached every time the page is refreshed as my code heavily depends on javascript calls so I just enabled it to make sure while I am still writing the code page reloads every time, the code is below as follows:
Util.js
var UtilModule = (function () {
var allowDebug = false;
var currentVersion = 0;
var properlyLoadScript = function (scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function () {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript(scriptPath)).done(function () {
callBackAfterLoadScript();
d.resolve("ok");
});
}
else {
console.log('Community loaded already and running now : ' + scriptPath);
callBackAfterLoadScript();
}
return d.promise();
};
var forceReloadScript = function (scriptPath) {
if (UtilModule.allowDebug) { debugger; }
var d = $.Deferred();
initCurrentVersion();
var JSLink = scriptPath + "?version=" + currentVersion;
var JSElement = document.createElement('script');
JSElement.src = JSLink;
JSElement.onload = customCallBack;
document.getElementsByTagName('head')[0].appendChild(JSElement);
function customCallBack() {
d.resolve("ok");
}
return d.promise();
};
var enableDebugger = function () {
allowDebug = true;
};
var disableDebugger = function () {
allowDebug = false;
};
var debugBreakPoint = function () {
if (allowDebug) {
}
};
var initCurrentVersion = function () {
if (currentVersion == 0) {
var dt = new Date();
var ttime = dt.getTime();
currentVersion = ttime;
}
};
var getCurrentVersion = function () {
return currentVersion;
};
return {
forceReloadScript,
properlyLoadScript,
enableDebugger,
disableDebugger,
debugBreakPoint,
allowDebug,
getCurrentVersion
};
})();
Note: I have made deferred objects to resolve only when the JSElement.onload has been called successfully. This step was taken just for testing purpose to make sure that I am not missing something before reaching a point to call the method where I am getting an error.
After that the code where I load scripts using UtilModule in my layout file look like as below:
_Layout.cshtml
<script src = "~/Scripts/Application/Modules/Util.js" ></script>
<script>
$.when(
UtilModule.properlyLoadScript('/Scripts/Application/Community.js', () => {
// Community.init() was supposed to be called here but i was still getting the error so i implemented this using promise that is returned from properlyLoadScript and call Community.init() further in .done callback to make sure that script is properly loading till this point.
//window.Community.init();
})
).done(function() {
window.Community.init();
});
</script>
#RenderSection("scripts", required: false)
Now coming to my main file where My index file is executing having (_layout.chsmtl) as parent layout
is
Index.cshtml
#{
ViewBag.Title = "My Blog";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<article id="BlogPage" style="margin: 5px;">
</article>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$.when(UtilModule.properlyLoadScript('/Scripts/Application/Modules/Blog.js', () => {
})).done(function () {
BlogModule.init();
});
});
//});
</script>
}
from what I know is that #section scripts is executed only once all the scripts in the layout page are loaded first so seems like a safe place to initialize the code which is dependent on some script in _Layout.HTML file and further enclosed with $(document).ready() for testing just to make sure that this script loads after everything else is loaded already.
Note: I am running all this code in in-cognito mode in chrome so nothing is cached while this code is running
now my Blog.js file looks like as below
var BlogModule = (function () {
var moduleReference = this;
var PageId = "#BlogPage ";
var currentUser;
var BlogPostList = [];
var blogPostInfo = {};
//init
var init = function () {
if (UtilModule.allowDebug) { debugger; }
//This is where the problem happens
console.log(window.Community);
console.log(window.Community.getUserInfo());
currentUser = window.Community.getUserInfo();
initBlogInformation();
//window.Community.registerModule(BlogModule);
if (Object.keys(window.Community.getUserProfileObject()) <= 0) {
$.when(window.Community.initUserProfile(currentUser.UserId)).then(function () {
$.when(initBlogInformation()).done(function () {
//debugger;
console.log(BlogPostList);
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
});
}
else {
$.when(initBlogInformation()).done(function () {
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
}
};
var loadBlogIndexMenuWidget = function () {
if (UtilModule.allowDebug) { debugger; }
};
var loadBlogPostWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogPostWidget";
widgetOptions.container = PageId + "#BlogPostWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
}
var loadBlogViewWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogViewWidget";
widgetOptions.container = PageId + "#BlogViewWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var loadBlogCommentsWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogCommentsWidget";
widgetOptions.container = PageId + "#BlogCommentsWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var initBlogList = function () {
$.when(getBlogPosts()).then(function (results) {
if (UtilModule.allowDebug) { debugger; }
BlogPostList = results.Record;
console.log(BlogPostList);
});
};
var getBlogPosts = function () {
if (UtilModule.allowDebug) { debugger; }
var d = new $.Deferred();
var uri = '/Blog/GetBlogPosts?userId=' + currentUser.UserId;
$.post(uri).done(function (returnData) {
if (UtilModule.allowDebug) { debugger; }
if (returnData.Status == "OK") {
BlogPostList = returnData.Record;
BlogPostList.map(x => {
if (UtilModule.allowDebug) { debugger; }
x.UserName = window.Community.getUserProfileObject().UserName;
if (x.Comments != null) {
x.CommentsObject = JSON.parse(x.Comments);
x.CommentsCount = x.CommentsObject.length;
}
});
console.log(returnData.Record);
d.resolve("ok");
} else {
window.Community.showNotification("Error", returnData.Record, "error");
d.resolve("error");
}
});
return d.promise();
};
var initBlogInformation = function () {
//debugger;
var d = $.Deferred();
getBlogPosts().then(getBlogModelTemplate()).then(function () {
d.resolve("ok");
});
return d.promise();
};
//Get Blog Model
var getBlogModelTemplate = function () {
var d = new $.Deferred();
var uri = '/Blog/GetBlogModel';
$.post(uri).done(function (returnData) {
blogPostInfo = returnData.Record;
d.resolve("ok");
});
return d.promise();
};
return {
init: init,
};
})();
The error I have highlighted below
so the problem is in init function of BlogModule which is BlogModule.init() the page is idle for too long and I reload it I get the following error:
cannot call
window.Community.getUserInfo() of undefined implying that community is undefied
after couple of refreshes its fine and the issue doesn't happen unless I change reasonable portion of code for js files to be recompiled again by browser or the browser is idle for too long and I am not able to understand what is triggering this issue.
below is log from console
p.s. error occurs more repeatedly if i refresh page with f5 but happens rarely if i refresh page with ctrl + f5
Please any help would be of great value
Answering my own question, took a while to figure it out but it was a small mistake on my end just fixing the following function in Util.js fixed it for me
var properlyLoadScript = function(scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function() {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript('/Scripts/Application/Community.js')).done(function() {
//debugger;
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
d.resolve("ok");
});
} else {
console.log('Community loaded already and running now : ' + scriptPath);
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
}
return d.promise();
};
I'm using CanJs and I'm learning jquery deferred but I have a problem.
I created a controller as sort of Singleton to manage data in IndexedDb.
First of all, I created an openDb function like this:
openDbDeferred: null,
openDb: function (dbName, dbVersion) {
console.log('Open DB...');
var openDbDeferred = this.openDbDeferred;
if (!openDbDeferred || openDbDeferred.isRejected()) {
openDbDeferred = $.Deferred();
var db;
var req = indexedDB.open(dbName, dbVersion);
req.onsuccess = function (evt) {
db = this.result;
console.log('openDB SUCCESS');
openDbDeferred.resolve(db);
};
req.onerror = function (evt) {
console.error("[ERROR] openDb: " + evt);
openDbDeferred.reject();
};
req.onupgradeneeded = function (evt) {
console.log('openDb.onupgradeneeded');
var db = evt.target.result;
var store = db.createObjectStore('sessioni', {keyPath: 'idSession'});
store.createIndex('by_url', 'url', {unique: false});
store.createIndex('by_startDate', 'startDate', {unique: false});
store.createIndex('by_endDate', 'endDate', {unique: false});
};
}
return openDbDeferred.promise();
}
Then I created a function to retrieve all data in DB:
getFilesList: function () {
var getDataDeferred;
return this.openDb('session-db', 1).then(function (db) {
console.log('Find all records...');
getDataDeferred = $.Deferred();
var tx = db.transaction("sessioni", "readwrite");
var store = tx.objectStore("sessioni");
var items = [];
tx.oncomplete = function() {
//console.log(items);
getDataDeferred.resolve(items);
console.log('Transazione getFilesList completata');
};
tx.onfailure = function(evt) {
getDataDeferred.reject();
console.error('[ERROR] Transazione getFilesList fallita: ' + evt);
};
var cursorRequest = store.openCursor();
cursorRequest.onsuccess = function (evt) {
var cursor = evt.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
};
cursorRequest.onerror = function (error) {
console.error('findAll [ERROR]: ' + error);
};
});
return getDataDeferred.promise();
}
I declared this controller in another controller to call getFilesList function:
retreiveAllData: function() {
return this.sessionManageModel.getFilesList().than(function(items) {
console.log(items)
return items;
});
}
When the retreiveAllData function is called, it returns 'undefined' because items is 'undefined'.
How can I obtain items in retreiveAllData function?
You've got two return statements in your getFilesList function. The second one should actually be inside the then callback - which currently returns undefined as you observe.
getFilesList: function () {
// no need to declare deferred variable outside of the callback
return this.openDb('session-db', 1).then(function (db) {
var getDataDeferred = $.Deferred();
… // do all the stuff
return getDataDeferred; // place the `return` here
});
// not here!
}
I have websocket service that works great when page is loaded. However, if connection is lost, and the service is trying to reconnect I am getting an error: "Uncaught ReferenceError: Service is not defined". Once I manually refresh page, service is working again. How can I reconnect without page refreshing? The app must reestablish that connection without any user involvement. This is my first angular app, so I am still in the process of learning the framework. Thank you.
angular.module('proApp').factory('webSocketService',
['$q', '$rootScope', function($q, $rootScope) {
var timeout = 2000;
var clearTimer = -1;
var port = '8081';
var server = '127.0.0.1';
var socket;
var host;
var Service = {};
function getSocketState() {
return (socket != null) ? socket.readyState : 0;
}
function onMessage(e) {
//console.log(e.data);
Service.message = JSON.parse(e.data);
$rootScope.$apply(function() {
Service.send();
});
}
//allows data to be used in controller
Service.send = function() {
$rootScope.$broadcast('broadcast');
};
function onError() {
clearInterval(clearTimer);
socket.onclose = function() {
};
clearTimer = setInterval("Service.getData()", timeout);
}
function onClose() {
clearInterval(clearTimer);
clearTimer = setInterval("Service.getData()", timeout);
}
function onOpen() {
clearInterval(clearTimer);
console.log("open" + getSocketState());
}
Service.getData = function() {
if ("WebSocket" in window) {
if (getSocketState() === 1) {
socket.onopen = onOpen;
clearInterval(clearTimer);
console.log(getSocketState());
} else {
try {
host = "ws://" + server + ":" + port + '';
socket = new WebSocket(host);
socket.onopen = onOpen;
socket.onmessage = function(e) {
onMessage(e);
};
socket.onerror = onError;
socket.onclose = onClose;
} catch (exeption) {
console.log(exeption);
}
}
}
};
// Public API here
return Service;
}]);
You have to change the use of setInterval to be like this:
clearTimer = setInterval(function () {
Service.getData();
}, timeout);
or just this:
clearTimer = setInterval(Service.getData, timeout);
This is the code I use, it can:
reconnect if connection is lost.
queue items while disconnected and send them on re-connection.
regular subscribing using the "listen" method.
"listenOnce" for an event once with a promise, after that the subscription is removed. Ideal for request/response using a correlationId
$rootScope.websocketAvailable indicates when the connection is available.
$rootScope.queuedMessages indicates when there are pending messages to be sent.
It is still part of a project in development, but I guess you can get the idea:
.service('$connection', ["$q", "$timeout", "websocketUrl", "$rootScope", function ($q, $timeout, websocketUrl, $rootScope) {
var connection = function () {
var me = {};
var listeners = [];
var oneListeners = [];
me.isConnected = false;
oneListeners.removeOne = function (listener) {
var index = oneListeners.indexOf(listener);
if(index!=-1)
oneListeners.splice(index, 1);
};
var correlationId = 0;
me.nextCorrelationId = function () {
return correlationId++;
};
$rootScope.queuedMessages = [];
me.listen = function (predicate, handler) {
listeners.push({ p: predicate, h: handler });
};
me.listenOnce = function (predicate, timeout) {
var deferred = $q.defer();
deferred.done = false;
var listener = { d: deferred, p: predicate };
oneListeners.push(listener);
if (timeout) {
$timeout(function () {
if (!deferred.done)
deferred.reject('timeout');
oneListeners.removeOne(listener);
}, timeout);
}
var promise = deferred.promise;
promise.then(function (data) {
deferred.done = true;
});
return promise;
};
var onopen = function () {
console.log('onopen');
$rootScope.websocketAvailable = true;
me.isConnected = true;
$rootScope.$$phase || $rootScope.$apply();
if ($rootScope.queuedMessages) {
for (var i = 0; i < $rootScope.queuedMessages.length; i++) {
ws.send(JSON.stringify($rootScope.queuedMessages[i]));
}
$rootScope.queuedMessages = null;
$rootScope.$$phase || $rootScope.$apply();
}
};
var onclose = function () {
console.log('onclose');
me.isConnected = false;
$rootScope.websocketAvailable = false;
$rootScope.$$phase || $rootScope.$apply();
$rootScope.queuedMessages = $rootScope.queuedMessages || [];
setTimeout(function () {
ws = connect();
}, 5000);
};
var onmessage = function (msg) {
console.log('onmessage');
var obj = JSON.parse(msg.data);
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
if (listener.p(obj))
listener.h(obj);
}
var remove = [];
for (var i = 0; i < oneListeners.length; i++) {
var listener = oneListeners[i];
if (listener.p(obj)) {
var o = obj;
listener.d.resolve(o);
remove.push(listener);
}
}
for (var i = 0; i < remove.length; i++) {
oneListeners.removeOne(remove[i]);
}
};
var onerror = function () {
console.log('onerror');
};
me.send = function (obj) {
if ($rootScope.queuedMessages)
$rootScope.queuedMessages.push(obj);
else
ws.send(JSON.stringify(obj));
}
var setHandlers = function (w) {
w.onopen = onopen;
w.onclose = onclose;
w.onmessage = onmessage;
w.onerror = onerror;
};
var connect = function () {
console.log('connecting...');
var w = new WebSocket(websocketUrl);
setHandlers(w);
return w;
}
var ws = connect();
return me;
};
return connection();
}])
I have the following code for getting records from indexeddb on chrome 30.
var IndexedDBStorage = function (name) {
// until we won't need this prefix mess
var indexedDB = window.indexedDB || window.webkitIndexedDB
|| window.mozIndexedDB || window.msIndexedDB;
var IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction;
var db;
// The initialization of our stuff
this.Supported = function () {
return indexedDB;
};
this.type = function () {
return "IndexedDB";
};
this.Setup = function () {
var dbVersion = 1.0;
var openRequest = indexedDB.open(name, dbVersion);
//handle setup - as the spec like it
openRequest.onupgradeneeded = function (e) {
console.log("running onupgradeneeded");
var thisDb = e.target.result;
if (!thisDb.objectStoreNames.contains(name)) {
var objectStore = thisDb.createObjectStore(name, {
autoIncrement: false
});
objectStore.createIndex("dataKey", "dataKey",
{ unique: false });
}
};
openRequest.onsuccess = function (e) {
db = e.target.result;
db.onerror = function (event) {
alert("Database error: " + event.target.errorCode);
console.dir(event.target);
};
if (db.setVersion) {
console.log("in old setVersion: " + db.setVersion);
if (db.version != dbVersion) {
var req = db.setVersion(dbVersion);
req.onsuccess = function () {
var ob = db.createObjectStore(name, {
autoIncrement: false
});
ob.createIndex("datakey",
"datakey", { unique: false });
var trans = req.result;
trans.oncomplete = function (ex) {
console.log("== trans oncomplete ==");
};
};
}
}
console.log(db);
};
};
this.GetAll = function (callback) {
console.log(db);
var transaction = db.transaction([name]); <-- gives error described below
var store = transaction.objectStore(name);
var items = [];
transaction.oncomplete = function (evt) {
callback(items);
};
var cursorRequest = store.openCursor();
cursorRequest.onerror = function (error) {
console.log(error);
};
cursorRequest.onsuccess = function (evt) {
var cursor = evt.target.result;
if (cursor) {
items.push({ key: cursor.key, body: cursor.value.body });
cursor.continue();
}
};
};
};
if i call it from a button like this :
it works fine if i do like this and call it from a button click, it works just fine:
function Init() { <-- called from script tag in index.html
$(document).ready(function () {
window.dataStore = new Store("data");
});
}
function getAll() { <-- button lick function
window.dataStore.getAll();
}
however, if i call it directly after initialization like this
function Init() {
$(document).ready(function () {
window.dataStore = new Store("data");
window.dataStore.GetAll();
});
}
i get a error with
Uncaught TypeError: Cannot call method 'transaction' of undefined
i am guessing it is because the db variable has not yet been globally set from openRequest.onsuccess when i call directly after init.
How can i fix this so it gets set properly
This is due the async behavior of the indexedDB API.
The db variable isn't assigned yet because the onsucces isn't called yet. To solve this you will have to provide a callback when the onsuccess is called on the openrequest, or you will have to delay the execution of the getAll call as long if the db variable is undefined.