add an object or edit if exist (indexeddb) - javascript

I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
var elements = document.getElementsByClassName('layers');
for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
index = object.index("by_Name");
request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));
request.onsuccess = function (e) {
var result = e.target.result;
if (result === undefined) {
var resultPut = object.put({
Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
Count: 1,
Type: String(elements[i].getAttribute("src").split("/")[4])
});
resultPut.onerror = function (e) {
alert(resultPut.error.name + '\n\n' + resultPut.error.message);
};
} else {
result.Count++;
var requestUpdate = object.put(result);
requestUpdate.onerror = function (event) {
alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
};
}
}(event);
}
}
alert("Finish");
})

The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
(function(myElement) {
if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
...
}
})(elements[i]);
}

Related

how to find index of array using substring value in javascript and replace with a new string?

I am getting string -
["1-2","10-4","2-3","3-1","4-4","5-2","6-4","7-3","8-1","9-2"]
as output from GetOption function where event - QuestionID & event1 -OptionID
Project-Online Examination System
var getValue;
var getName = new Array();
var temp = new Array();
function GetOption(event, event1) {
debugger;
if (temp.includes(event)) {
var x = getName.indexOf(event);
getName.splice(x - 1, 1);
getName.includes(event);
}
this.event1 = event1;
temp.push(event);
var getValue = event + "-" + event1;
if (getValue == "undefined-undefined") {
getName.push("");
} else {
getName.push(getValue);
getName.sort();
alert(getName);
}
$("#resultHidden").val(getName);
}
var items = ["1-2","10-4","2-3","3-1","4-4","5-2","6-4","7-3","8-1","9-2"];
var searchItems = "1-2";
var newItems = "2-1";
for (var i = 0; i < items.length; i++) {
if (items[i].startsWith(searchItems)) {
items[i] = newItems;
}
}

Convert to CSV in a downloadable format

I want to convert an array of objects into CSV.
Please have a look at the code. What I am doing wrong? I am getting an array when I console.log("csv",array) which is passed from printAccountsGa. Moreover, I have declared JSONGA = [] globally but still I get array with every object on consoling. But when I pass that to csvConverter function it displays undefined.
function printAccountsGa(results) {
if (results && !results.error) {
var accounts = results.items;
for (var i = 0, account; account = accounts[i]; i++) {
//console.log('Account Id: ' + account.id);
listProperties(account.id);
//console.log('Account Name: ' + account.name);
}
console.log(JSONGA);
csvConverter(JSONGA);
}
}
function printAccountsGtm(results) {
console.log("result is",results);
if (results && !results.error) {
var accounts = results.accounts;
console.log(accounts);
for (var i = 0, account; account = accounts[i]; i++) {
//console.log('Account Id: ' + account.accountId);
listContainers(account.accountId);
//console.log('Account Name: ' + account.name);
}
}
}
function listProperties(accountID){
var request = gapi.client.analytics.management.webproperties.list({
'accountId': accountID
});
request.execute(printProperties);
}
function printProperties(results){
if (results && !results.error) {
var properties = results.items;
//console.log(properties[0].accountId);
$.each(properties,function(element){
//console.log(properties[element].accountId);
var tempObj={};
tempObj={
'AccountID':properties[element].accountId,
'PropertyID':properties[element].id,
'name':properties[element].name,
}
JSONGA.push(tempObj);
})
}
}
function csvConverter(array){
console.log("csv",array);
var result = array.map(function(d){
return JSON.stringify(values(d));
})
.join('\n')
.replace(/(^\[)|(\]$)/mg, '');
window.open('data:text/csv;charset=utf-8,' + escape(result));
}
window.onload = function(){
var el = document.getElementById('auth-button-ga');
el.addEventListener('click', authorizeGa);
var elt = document.getElementById("auth-button-gtm");
elt.addEventListener('click', authorizeGtm);
}

how can i return the count from a function

hi iam new to javascript, i am trying to return a count from the function my code is like below
my code
function moredbCount(contentMoreArray2, ArrHeading) {
var sampleArr = [];
for (var a = 0; a < contentMoreArray2.length; a++) {
if (ArrHeading !== 'More') {
var fullHeading = ArrHeading + '-' + contentMoreArray2[a].name;
} else {
fullHeading = contentMoreArray2[a].name;
}
sampleArr.push(fullHeading);
}
var sampleCount = sampleHeadingCount(sampleArr);
return sampleCount.then(function (resultantCount) {
return resultantCount; //Here iam getting some count like 10 and returning it to the function;
});
}
var contentCount;
var totalCount = moredbCount(contentMoreArray2, ArrHeading);
totalCount.then(function (resultantTotalCount) {
return contentCount = resultantTotalCount
});
// Here i want to use contentCount 10, But iam getting undefined
Thanks In advance
return contentCount = resultantTotalCount won't return the count, but rather the response of assignment. In contentCount = resultantTotalCount, you are basically assigning the value of resultantTotalCount to contentCount.
You should use
function moredbCount(contentMoreArray2, ArrHeading) {
var sampleArr = [];
for (var a = 0; a < contentMoreArray2.length; a++) {
if (ArrHeading !== 'More') {
var fullHeading = ArrHeading + '-' + contentMoreArray2[a].name;
} else {
fullHeading = contentMoreArray2[a].name;
}
sampleArr.push(fullHeading);
}
var sampleCount = sampleHeadingCount(sampleArr);
return sampleCount.then(function (resultantCount) {
return resultantCount; //Here iam getting some count like 10 and returning it to the function;
});
}
var contentCount;
var totalCount = moredbCount(contentMoreArray2, ArrHeading);
totalCount.then(function (resultantTotalCount) {
return resultantTotalCount
});

Hash key access error

I'm having this weird error while accessing the key evenimente of my object. Any ideas why?
It clearly is available but I cannot access it via .(dot)
EDIT: Sorry, here is the code
var isPresent = function(entry) {
var evenimente = entry.evenimente;
var elem = $("#" + entry.nume + "-" + entry.prenume);
for(var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if(eveniment.eveniment_id == eventId && eveniment.user_id == entry.id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}
I get entry via ajax from the server
Looks like your entry is an array (see the [ and ] in your console).
So, you should be able to access the evenimente field this way:
var ev = entry[0].evenimente
The updated code would look like this:
var isPresent = function (entry) {
var evenimente = entry[0].evenimente;
var elem = $("#" + entry[0].nume + "-" + entry[0].prenume);
for (var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if (eveniment.eveniment_id == eventId && eveniment.user_id == entry[0].id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}
Also, for convenience, you could just override the entry value like below:
var isPresent = function (entry) {
entry = entry[0];
if (!entry) {
throw new Error("No available entry.");
}
var evenimente = entry.evenimente;
var elem = $("#" + entry.nume + "-" + entry.prenume);
for (var i = 0; i < evenimente.length; i++) {
var eveniment = evenimente[i];
if (eveniment.eveniment_id == eventId && eveniment.user_id == entry.id) {
elem.prop('checked', true);
}
}
elem.prop('checked', false);
}

Javascript Callback in for Loop

My problem is that I'm having a Function A which calls at one point another function, let's call it Function B (getChildContent) and needs the return value of Function B in order to proceed. I know that it's because of Javascripts Asynchronous Nature, and i tried to solve it with a callback. But i can't get it work properly.
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
//var content = getChildContent(caps[y]);
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}}}
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
So in Function A I'm trying to call getChildContent from a for-Loop and pass the current string from caps-array. For each String in caps-array getChildContent() makes a http request over a node.js module and retrieves a string. With this string i'm building an object (content) which is needed in Function A to continue. However the 'console.log(content)' in Function A just prints out the object which is created with the last string in caps-array, but for many times. E.G. if caps-array has 5 entries, i get 5 times the object which is created with the last entry of caps-array.
How can i manage the loop/callback to get every time the right object on my console?
Your loop should call another function that preserves the value of y, something like this:
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
yourNewFunction (y, caps, parent);
}}}
}
function yourNewFunction (y, caps, parent) {
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
There are 2 ways to do so.
Put the loop inside a function, execute your callback after the loop is done. (Problematic if you are doing async call inside the loop.
function doLoopdiloopStuff() {
for() {
}
callback();
}
The other way, the way i prefer looks like this:
for(var i = 0; i < stuff || function(){ /* here's the callback */ }(), false; i++) {
/* do your loop-di-loop */
}
In another example:
for (var index = 0; index < caps.length || function(){ callbackFunction(); /* This is the callback you are calling */ return false;}(); index++) {
var element = caps[index];
// here comes the code of what you want to do with a single element
}

Categories

Resources