When can I tell that I have opened a connection in indexedDB? - javascript

In the getCursor_ function below, please explain how I could determine if IndexedDb has opened and if not re-run function once it has? The getCursor_ runs correctly. However, since all of these calls are asynchronous, the function fails when executing before the database has completed opening.
This code is executed in a separate process:
var ixDb;
var ixDbRequest;
ixDbRequest = window.indexedDB.open(dbName, dbVersion);
ixDbRequest.onsuccess = function (e) {
ixDb = ixDbRequest.result || e.result;
};
The getCursor_ function below works fine unless ixDbRequest has not completed execution. I figured out how to test for that, but I am not sure how to wait in the instance where the open database request is still running.
function getCursor_(objectStoreName) {
if (!ixDb) {
if (ixDbRequest) {
// "Database is still opening. Need code to wait or re-run
// once completed here.
// I tried the following with no luck:
ixDbRequest.addEventListener ("success",
getCursor_(objectStoreName), false);
return;
}
}
var transaction = ixDb.transaction(objectStoreName,
IDBTransaction.READ_ONLY);
var objectStore = transaction.objectStore(objectStoreName);
try{
var request = objectStore.openCursor();
return request;
}
catch(e){
console.log('IndexedDB Error' + '(' + e.code + '): ' + e.message);
}
}
UPDATE BELOW:
The answer from #Dangerz definitely helped put me on the right track. However, since the function call is asynchronous, I also ended up having to add a callback in order to actually be able to use the cursor once the "success" event finally fired, and I was able to get the requested IndexedDb cursor. The final working function is below (re-factored slightly to remove the negative logic above "if(!ixDb)" . I am totally open to suggestions, if anyone sees room for improvement!
//****************************************************************************
//Function getCursor - Returns a cursor for the requested ObjectStore
// objectStoreName - Name of the Object Store / Table "MyOsName"
// callback - Name of the function to call and pass the cursor
// request back to upon completion.
// Ex. getCursor_("ObjectStore_Name", MyCallBackFunction);
// Function MyCallBackFunction(CursorRequestObj) {
// CursorRequestObj.onsuccess =
// function() {//do stuff here};
// }
//****************************************************************************
function getCursor_(objectStoreName, callback) {
//The the openCursor call is asynchronous, so we must check to ensure a
// database connection has been established and then provide the cursor
// via callback.
if (ixDb) {
var transaction =
ixDb.transaction(objectStoreName, IDBTransaction.READ_ONLY);
var objectStore = transaction.objectStore(objectStoreName);
try{
var request = objectStore.openCursor();
callback(request);
console.log('ixDbEz: Getting cursor request for '
+ objectStoreName + ".");
}
catch(e){
console.log('ixDbEz Error' + ' getCursor:('
+ e.code + '): ' + e.message);
}
}
else {
if (ixDbRequest) {
ixDbRequest.addEventListener ("success"
, function() { getCursor_(objectStoreName, callback); }
, false);
}
}
}

Change your addEventListener line to:
ixDbRequest.addEventListener ("success", function() { getCursor_(objectStoreName) }, false);

Related

How to break a callback chain in JavaScript?

I am uploading multiple files from a browser and need to do so sequentially.
So I chain the next upload commencement from the previous upload completion callback.
It's simple and works just fine.
During the upload I display the progress to the user along with a cancel button.
If the user hits cancel I want to stop the entire callback chain.
How would I do that? Is there some mechanism in JavaScript to halt my callback chain?
OK here is an example of a callback chain in JavaScript. The question is, how to break it from a "cancel" button?
https://jsfiddle.net/jq7m9beq/
var filenamesToProcessQueue = ['v.jpg','w.jpg','x.jpg','y.jpg','z.jpg']
function finishedProcessing (filename) {
console.log('finished processing: ' + filename)
// processing finished for this file, start again by chaining to the next one
doProcessFiles()
}
function waitForEachFile (filename, callback) {
// wait a couple of seconds and log the filename
setTimeout(function(){ console.log('Waited 2 seconds for: ' + filename);callback(filename);}, 2000)
}
function doProcessFiles() {
// get next file to process and remove it from the queue at same time
filename = filenamesToProcessQueue.pop()
// if the file is undefined then the queue was empty
if (typeof filename !== 'undefined') {
console.log('Process ' + filename)
waitForEachFile(filename, finishedProcessing)
}
}
doProcessFiles()
On click of a cancel button, set a flag
var cancelFlag = false;
document.getElementById("cancelBtn").addEventListener("click", function(){
cancelFlag = true;
//other code
});
change your doProcess to
function doProcessFiles()
{
if (cancelFlag)
{
return false; //this will break the chain
}
// get next file to process and remove it from the queue at same time
filename = filenamesToProcessQueue.pop()
// if the file is undefined then the queue was empty
if (typeof filename !== 'undefined')
{
console.log('Process ' + filename)
waitForEachFile(filename, finishedProcessing)
}
}
You can also stop your waiting
function waitForEachFile (filename, callback)
{
if (cancelFlag)
{
return false; //this will stop waiting as well
}
// wait a couple of seconds and log the filename
setTimeout(function(){ console.log('Waited 2 seconds for: ' + filename);callback(filename);}, 2000)
}
you can set the flag in the cancel button itself
document.getElementById("cancelBtn").setAttribute("data-flag", "true");
and check this value
var cancelFlag = Boolean(document.getElementById("cancelBtn").getAttribute("data-flag"));

Strophe.js client connecting to server, disconnect/timeout

I have a little JavaScript XMPP client, written with Strophe, that connects to a server hosted on hosted.im. I think hosted.im uses ejabberd on their backend.
I establish the connection using
Strophe.Connection(myBoshService), and am able to send chat messages back and forth. However, after a certain time, it seems, there is an automatic disconnect if there is no activity.
Now, my question is, what would be a good way to keep the session active, so that it does not disconnect. Disconnect time seems to be very short, about 60 seconds or so.
Should I send some kind of activity back and forth to keep it open? Or, which seems simpler to me, should I somehow change the timout of the session. If so, where can I change this? Is this a server-setting, irregardless of the Strophe.Connection object, or can I set the timeout when initializing Strophe.Connection?
Thanks for any and all help.
Best regards,
Chris
Edit: Here is the code I use for connecting:
I manage the connection through a global variable Hello (yes, name is awkward, I took it from an example):
var Hello = {
connection: null,
start_time: null,
partner: {
jid: null,
name: null
},
log: function (msg) {
$('#log').append("<p>" + msg + "</p>");
},
send_ping: function (to) {
var ping = $iq({
to: to,
type: "get",
id: "ping1"}).c("ping", {xmlns: "urn:xmpp:ping"});
Hello.log("Sending ping to " + to + ".");
console.log("Sending ping to " + to + ".");
Hello.start_time = (new Date()).getTime();
Hello.connection.send(ping);
},
handle_pong: function (iq) {
var elapsed = (new Date()).getTime() - Hello.start_time;
Hello.log("Received pong from server in " + elapsed + "ms.");
console.log('Received pong from server in " + elapsed + "ms.');
$('#login').hide();
$('#chat').show();
//window.location = "chat.html";
//Hello.connection.disconnect();
return true;
},
//"<active xmlns="http://jabber.org/protocol/chatstates"/><body xmlns="http://jabber.org/protocol/httpbind">tuiuyi</body>"
displayIncomingText: function (text) {
var body = $(text).find("xml > body");
if (body.length === 0)
{
body = $(text).find('body');
if (body.length > 0)
{
body = body.text();
$('#chattext').append("<p>"+ body + "</p>");
}
else
{
body = null;
}
}
return true;
},
readRoster: function (iq) {
$(iq).find('item').each(function () {
var jid = $(this).attr('jid');
var name = $(this).attr('name') || jid;
Hello.partner.name = name;
Hello.partner.jid = jid;
});
return true;
}
};
The main relevant objects here are Hello.connect and Hello.partner, which stores the jid of the only person on the accounts roster, as this is a one to one chat.
Then, in $(document).ready, I bind two buttons to connect and send messages respectively:
$(document).ready(function () {
$('#chat').hide();
$('#chatSend').bind('click', function () {
Hello.connection.send(
$msg(
{to : Hello.partner.jid, type : 'chat'}
).c('body').t($('#chattextinput').val())
);
$('#chattext').append("<p align='right'>" + $('#chattextinput').val() + "</p>");
});
$('#SignIn').bind('click', function () {
$(document).trigger('connect', {
jid: $('#eMail').val(), password: $('#password_f').val()
}
);
});
});
Clicking the sign-in button triggers the event "connect":
$(document).bind('connect', function (ev, data) {
console.log('connect fired');
var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
console.log('callback being done');
if (status === Strophe.Status.CONNECTED) {
alert('connected!');
$(document).trigger('connected');
alert('Connected successfully');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
else
{
Hello.log("error");
console.log('error');
}
});
Hello.connection = conn;
});
This creates the Strophe.Connection and stores it in Hello.connection. Also, it sets the callback function of the connection object. This code is taken straight from an example in a Strophe.js book. Anyway, the callback checks the status of the connection, and if status === Strophe.Status.DISCONNECTED, triggers "disconnected", which only does this:
$(document).bind('disconnected', function () {
Hello.log("Connection terminated.");
console.log('Connection terminated.');
// remove dead connection object
Hello.connection = null;
});
Anyway, what is happening is that, for some reason, in the callback set with conn.connect, after a short time, the status evaluates to Strophe.Status.DISCONNECTED, and I am not sure why, unless somewhere, either in the server or in the connection object, there is a timeout specified which seems to be ca. 60 seconds.
As to a log of the stanzas going back and forth, I guess I would need to quickly write a handler to see all incoming stanzas, or is it possible to see a log of all stanzas between the client and server in ejabberd?
For the sake of other people who come upon this and have a similar problem, the solution in this case was that the servers at hosted.im send a ping request every 60 seconds to check if the client is still online.
This ping request looks like this:
<iq from="testserver.p1.im" to="chris#testserver.p1.im/23064809721410433741569348" id="164323654" type="get"> <ping xmlns="urn:xmpp:ping"></ping> </iq>
What is needed, of course, is to form a response, which will look something like this:
<iq from="chris#testerver.p1.im" to="testserver.p1.im" id="164323654" type="result" xmlns="jabber:client"><ping xmlns="urn:xmpp:ping"/></iq>
Note the "to"-attribute. I omitted it at the beginning as I was under the assumption a message sent with no to-attribute is automatically assumed to be a client->server message. Not in this case however. Not sure if this is the case in general, or whether it is an oddity of servers at hosted.im.
Thanks to everyone for their comments and suggestions!
Best regards,
Chris

Why is the JavaScript console saying my variable is undefined, even when I defined it two lines before?

I'm using WebSockets to connect to a remote host, and whenever I populate realData and pass it to grapher(), the JavaScript console keeps telling me realDatais undefined. I tried checking the type of the data in the array, but it seems to be fine. I've called grapher() before using an array with random data, and the call went through without any problems. With the data from the WebSocket, however, the call will always give me "error: realData is not defined". I'm not sure why this is happening. Here is the code I used:
current.html:
var command = "Hi Scott"
getData();
function getData()
{
console.log("getData is called");
if("WebSocket" in window)
{
var dataCollector = new WebSocket("ws://console.sb2.orbit-lab.org:6100",'binary');
dataCollector.binaryType = "arraybuffer";
console.log(dataCollector.readyState);
dataCollector.onopen = function()
{
//alert("The WebSocket is now open!");
console.log("Ready state in onopen is: " + dataCollector.readyState);
dataCollector.send(command);
console.log(command + " sent");
}
dataCollector.onmessage = function(evt)
{
console.log("onmessage is being called");
var realData = new Uint8Array(evt.data);
console.log(realData);
grapher(realData); //everything up to this point works perfectly.
}
dataCollector.onclose = function()
{
alert("Connection to Server has been closed");
}
return (dataCollector);
}
else
{
alert("Your browser does not support WebSockets!");
}
}
graphing.js:
function grapher(realData)
{
console.log("grapher is called");
setInterval('myGraph(realData);',1000); //This is where the error is. I always get "realData is not defined".
}
function myGraph(realData)
{
/*
for(var i = 0; i < SAarray.length; i++) // Loop which will load the channel data from the SA objects into the data array for graphing.
{
var data[i] = SAarray[i];
}
*/
console.log("myGraph is called");
var bar = new RGraph.Bar('channelStatus', realData);
bar.Set('labels', ['1','2','3','4','5','6','7','8']);
bar.Set('gutter.left', 50);
bar.Set('gutter.bottom', 40);
bar.Set('ymax',100);
bar.Set('ymin',0);
bar.Set('scale.decimals',1);
bar.Set('title','Channel Status');
bar.Set('title.yaxis','Status (1 is on, 0 is off)');
bar.Set('title.xaxis','Channel Number');
bar.Set('title.xaxis.pos',.1);
bar.Set('background.color','white');
bar.Set('colors', ['Gradient(#a33:red)']);
bar.Set('colors', ['red']);
bar.Set('key',['Occupied','Unoccupied']);
bar.getShapeByX(2).Set('colors',barColor(data[0]));
bar.Draw();
}
Because strings (as code) passed to setInterval execute in the global scope, therefore the realData parameter isn't available. There's rarely a good reason to pass a string to setInterval. Instead, use:
setInterval(function () {
myGraph(realData);
}, 1000);
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
Try it without it needing to evaluate a string:
setInterval(function() {
myGraph(realData);
},1000);
Any time you are using setTimeout or setInterval, you should opt for passing an actual function instead of a string.

While loop in Javascript with a Callback

I am trying to write the Pseudocode given here https://dev.twitter.com/docs/misc/cursoring with javascript using node-oauth https://github.com/ciaranj/node-oauth. However I am afraid because of the nature of the callback functions the cursor is never assigned to the next_cursor and the loop just runs forever. Can anyone think a workaround for this?
module.exports.getFriends = function (user ,oa ,cb){
var friendsObject = {};
var cursor = -1 ;
while(cursor != 0){
console.log(cursor);
oa.get(
'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
,user.token //test user token
,user.tokenSecret, //test user secret
function (e, data, res){
if (e) console.error(e);
cursor = JSON.parse(data).next_cursor;
JSON.parse(data).users.forEach(function(user){
var name = user.name;
friendsObject[name + ""] = {twitterHandle : "#" + user.name, profilePic: user.profile_image_url};
});
console.log(friendsObject);
}
);
}
}
Suppose your code is wrapped in a function, I'll call it getFriends, basically it wraps everything inside the loop.
function getFriends(cursor, callback) {
var url = 'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false'
oa.get(url, user.token, user.tokenSecret, function (e, data, res) {
if (e) console.error(e);
cursor = JSON.parse(data).next_cursor;
JSON.parse(data).users.forEach(function(user){
var name = user.name;
friendsObject[name + ""] = {twitterHandle : "#" + user.name, profilePic: user.profile_image_url};
});
console.log(friendsObject);
callback(cursor);
});
}
In nodejs all io is done asynchronously, so you will loop a lot more than needed, before actually changing cursor, what you need is loop only when you receive a response from the Twitter API, you could do something like this:
function loop(cursor) {
getFriends(cursor, function(cursor) {
if (cursor != 0) loop(cursor);
else return;
});
}
You start it by calling loop(-1), of course this is just one way of doing it.
If you prefer you could use an external library, like async.
I strongly suggest using async for this. It's made for situations like yours and handles concurrency and execution for you. You will simply end up writing something that does the same thing as async, only yours will not be as tested.

onsuccess and oncomplete call back is not working for indexedDb add transaction

I am trying to have a function in the onsuccess callback for IndexedDb add transaction, but for some reason the onsuccess callback is never called. I basically tried to add a movie object to the IndexedDb and in the callback I try to display all the movies in the indexedDb by iterating cursor. I hope that the newly added movie will also be displayed. But the callback is failing. Below is my code. Could someone please let me know what is the problem?
var movieName=document.getElementById('movieInput').value;
var movieDataToStore = [{ movieid: "5", name: movieName, runtime:"60"}];
var request = indexedDB.open("movies", 1);
request.onsuccess = function(event) {
db = event.target.result;
//var transaction = window.db.transaction(["movies"], "readwrite");
//alert(db.transaction("movies").objectStore("movies").add(null));
var requestDataadd=window.db.transaction(["movies"],"readwrite").objectStore("movies").add(movieDataToStore[0]);
requestDataadd.onsuccess = function(event) {
window.db.transaction("movies").objectStore("movies").openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("CURSOR: movie: " + cursor.key + " has name " + cursor.value.name);
cursor.continue();
} else {//writeLog("CURSOR: No more entries!");
alert("Cursor at the Load Button unabe to open");
}
};
};
};
You are using two transactions. Since the second transaction is created before the first is completed, both of them are getting snapshot of initial state.
You have to reuse the first transaction or wait until it is completed to start second transaction. Here is reusing the transaction:
var tx = window.db.transaction(["movies"],"readwrite");
var requestDataadd = tx.objectStore("movies").add(movieDataToStore[0]);
requestDataadd.onsuccess = function(event) {
tx.objectStore("movies").openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("CURSOR: movie: " + cursor.key + " has name " + cursor.value.name);
cursor.continue();
} else {//writeLog("CURSOR: No more entries!");
alert("Cursor at the Load Button unabe to open");
}
};
};
Are you getting the alert "Cursor at the Load Button unabe to open" ?
On first glance, I think the problem would be that the requestDataadd request fails because you already have inserted this object once before (successfully), and so you get a duplicate key error. But you don't have an onerror listener defined for the requestDataadd request.
However, that can't be the case if the onsuccess listener of requestDataadd actually is called (and you get an alert).
I also see you don't have an onerror listener defined for the openCursor request. You might want to change that to get more insight. Generally, you should always define both onerror and onsuccess handlers.

Categories