when I execute this function it displays me the following error:
"JavaScript execution exceeded timeout" how I can solve this problem by using settimeout () or what?
I retrieve 3000 line from json file.
applyChanges_PhrasesTypes: function(employees, callback) {
//alert("fonction apply chamges est lancer PhrasesTypes");
this.db.transaction(
function(tx) {
var l = employees.length;
var sql =
"INSERT OR REPLACE INTO PhrasesTypes (IdPhrase, IdPhraseES, IdRubrique, IdTypeTravauxAffichage, Phrase, AidePhrase, AvertissementPhrase,OrdrePhrase,QuotationParDefaut,Published) " +
"VALUES (?,?,?,?,?,?,?,?,?,?)";
//alert('Inserting or Updating in local database: PhrasesTypes');
var e;
for (var i = 0; i < l; i++)
{
e = employees[i];
log(i);
//log("Ligne "+ i +" est inserer de id PhrasesTypes = "+e.IdPhrase);
var params = [e.IdPhrase, e.IdPhraseES, e.IdRubrique, e.IdTypeTravauxAffichage, e.Phrase, e.AidePhrase, e.AvertissementPhrase,e.OrdrePhrase,e.QuotationParDefaut,e.Published];
tx.executeSql(sql, params);
}
log('sync_PhrasesType shronization terminée avec (' + l + ' items sync_PhrasesTypeshronié)');
},
this.txErrorHandler_PhrasesTypes,
function(tx)
{
callback();
}
);
}
#lgor: here is my code but only 2000 insert line, and terminates with an error,
JavaScript execution exceeded timeout javascript
InsertPortion: function(tx)
{
var l = Math.min(gEmployees.length, gIter + 300);
log('aaaaaaaaaaaaaaaaaaaaaaaa---'+l)
for (; gIter<l ; gIter++)
{
log('do insert here');
var sql =
"INSERT OR REPLACE INTO PhrasesTypes (IdPhrase, IdPhraseES, IdRubrique, IdTypeTravauxAffichage, Phrase, AidePhrase, AvertissementPhrase,OrdrePhrase,QuotationParDefaut,Published) " +
"VALUES (?,?,?,?,?,?,?,?,?,?)";
//alert('Inserting or Updating in local database: PhrasesTypes');
var e;
e = gEmployees[gIter];
log(gIter);
//log("Ligne "+ i +" est inserer de id PhrasesTypes = "+e.IdPhrase);
var params = [e.IdPhrase, e.IdPhraseES, e.IdRubrique, e.IdTypeTravauxAffichage, e.Phrase, e.AidePhrase, e.AvertissementPhrase,e.OrdrePhrase,e.QuotationParDefaut,e.Published];
tx.executeSql(sql, params);
}
if (gIter < gEmployees.length)
{
log('sync_PhrasesType shronization terminée avec (' + gIter+ ' items sync_PhrasesTypeshronié)');
setTimeout(dao3.InsertPortion(tx), 100);
}
else
{
gEmployees = null;
gIter = 0;
}
},
applyChanges_PhrasesTypes: function(employees, callback) {
//alert("fonction apply chamges est lancer PhrasesTypes");
this.db.transaction(
function(tx)
{
gIter = 0;
gEmployees = employees;
dao3.InsertPortion(tx);
},
this.txErrorHandler_PhrasesTypes,
function(tx)
{
callback();
}
);
},
Consider converting the loops in your code to async calls.
Take a look at https://github.com/caolan/async
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I am writing data to firebase using a loop and async function. I am using promises to get the result of query and want to display success message when all of data is inserted. I can not figure out what I am doing wrong. I know it has a small bug. Can anyone help me?
CODE:
async function submitAttendance() {
var uploadPromises = [];
for (var j = 0; j < i; j++) {
uploadPromises.push(
new Promise((resolve, success) => {
var naid = "name" + j + "";
var na = document.getElementById(naid).innerHTML + "";
var stid = "status" + j + "";
var stat = document.getElementById(stid).value + "";
var uidid = "uid" + j;
var uidstu = document.getElementById(uidid).innerHTML + "";
var attinfo = {
student_Id: uidstu,
student_attendanceValue: stat,
student_class: clstd,
student_name: na
};
db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
console.log(attinfo);
});
})
)
}
await Promise.all(uploadPromises)
alert("Attendance Marked Successfully");
}
uploadPromises.push(
new Promise((resolve, success) => {
...
db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
console.log(attinfo);
resolve();
});
})
)
You need to resolve inside your promise somewhere. Presumably in the .then of your db interaction
However, rather than returning a manually created promise, you may consider pushing the db interaction itself if it is a promise, which it looks like:
for (var j = 0; j < i; j++) {
var naid = "name" + j + "";
var na = document.getElementById(naid).innerHTML + "";
var stid = "status" + j + "";
var stat = document.getElementById(stid).value + "";
var uidid = "uid" + j;
var uidstu = document.getElementById(uidid).innerHTML + "";
var attinfo = {
student_Id: uidstu,
student_attendanceValue: stat,
student_class: clstd,
student_name: na
};
uploadPromises.push(
db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
console.log(attinfo);
});
)
}
I have a problem with my page. It works on localhost (WebServ). On my vps (Debian 8) it not work.
You can look: http://www.csgobeton.pl/withdraw.
When you do recaptcha it says "syntax error unexpected end of input".
In the console I can see there is a problem at line "data = JSON.parse(data);".
Please help me.
function loadLeft(opts) {
inlineAlert("", "Loading your inventory - please wait...");
var DIV = "<div class='placeholder matched' data-name='{0}' data-pos='{1}'
data - price = '{2}'
data - bot = '{3}' > ";
DIV += "<div class='slot {13}' data-view='{15}' data-name='{4}' data-
pos = '{5}'
data - price = '{6}'
data - bot = '{7}'
data - id = '{8}'
style = 'background-
image: url(\"{9}\")'>"; DIV += "<div class='name'>{10}</div>"; DIV +=
"<div class='price {11}'>{12}</div>"; DIV +=
"<div class='bot'>{14}</div>"; DIV += "</div></div>";
var IMG = "{0}/{1}fx{2}f";
var url = "";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "http://www.csgobeton.pl/get_bank_safe?g-recaptcha-response=" + g;
}
$.ajax({
url: url,
success: function (data) {
$("#inlineAlert").html("data");
try {
data = JSON.parse(data);
if (data.success) {
console.log(data);
$("#left .reals").empty();
$("#right .reals").empty();
$("#right .bricks").removeClass("hidden");
$("#avail").html(formatNum(data.balance));
var count = data.items.length;
var eleA = [];
for (var i = 0; i < count; i++) {
var item = data.items[i];
var url = IMG.format(item.img, 110, 50);
var price_class = "ball-1";
if (DEPOSIT) {
price_class = "ball-0";
}
var slot_class = "";
var price_content = item.price;
if (price_content == 0) {
price_content = item.reject;
slot_class = "reject";
} else {
price_content = formatNum(price_content);
}
bot = 0;
if (item.botid) {
bot = item.botid;
}
var botLabel = "";
if (!DEPOSIT) {
botLabel = "Bot " + bot;
}
var ele = DIV.format(item.name, i, item.price, bot,
item.name, i, item.price, bot, item.assetid, url, item.name,
price_class,
price_content, slot_class, botLabel, item.view);
eleA.push(ele);
}
$("#left_number").html(count);
document.getElementById("left").getElementsByClassName(
"reals")[0].innerHTML = eleA.join('');
addPadding("#left", 6);
if (data.fromcache) {
inlineAlert("success", "Loaded " + count + " items from
cache - < a href = \
"javascript:loadLeft('nocache')\">reload inventory</a>"
);
} else {
inlineAlert("success", "Loaded " + count + " items.");
}
} else {
inlineAlert("error", data.error);
if (data.count > 0) {
cmd();
}
}
if (data.tid) {
showPending(data);
}
} catch (err) {
inlineAlert("error", "Javascript error22: " + err);
console.log(err.stack);
}
},
error: function (err) {
inlineAlert("error", "AJAX error: " + err.statusText);
},
});
}
index.php is:
case 'get_bank_safe':
if(!$user) exit(json_encode(array('success'=>false, 'error'=>'You must
login to access the widthdraw.')));
$g = curl('https://www.google.com/recaptcha/api/siteverify?secret=6Le-
6R8TAAAAAAjgt_wfQMOUCMxCCAWs-iFlP9T-&response='.$_GET['g-recaptcha-response']);
$g = json_decode($g, true);
if($g['success'] == true) {
$array =array('balance'=>$user['balance'],'error'=>'none','items'=>array(),'success'=>true);
mysql_query('SET CHARACTER SET utf8');
$sql = $db->query('SELECT * FROM `items` WHERE `status` = 1');
$prices = file_get_contents('prices.txt');
$prices = json_decode($prices, true);
while ($row = $sql->fetch()) {
$array['items'][] =
array('botid'=>$row['botid'],'img'=>'http://steamcommunity-a.akamaihd.net/economy/image/'.$row['img'],'name'=>$row['market_hash_name'],'ass
etid'=>$row['id'],'price'=>$prices['response']['items']
[$row['market_hash_name']]['value']*10,'reject'=>'unknown items');
}
exit(json_encode($array));
}
break;
The result of get_safe_bank is:
{"balance":"0","error":"none","items": [{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}{"balance":"0","error":"none","items":[{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}
When I paste it instead data = JSON.parse(data); data it works correctly.
I am trying to open the serial port 2 on my beagle bone, using the following code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
The complete code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
b.pinMode("P9_17", b.OUTPUT);
var countTry =2;
var i = 0; // to loop over the array
var waiting_interval = 3000; // waiting for every slave to reply
var deli;
var slaves = ["S1", "S2" , "S3", "S4", "S5", "S6"];
var counter=[0 , 0 , 0 , 0 ,0 ,0];
var slave_exists = false;
serialPort.on('open',function onSerialOpen(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
i--;
if(data.search("END" + slaves[i]) ==0){
console.log("ENDED");
slave_exists = true;
counter[i]=0;
}
else{
// if(data!="END" + slaves[i]){
if(data.search("END" + slaves[i])!==0){
deli = data.indexOf(":");
var parameter = data.substring(0, deli);
var value = data.substring(deli +1);
console.log("parameter is: " + parameter + " - Value is: " + value);
}
}
if(slave_exists){
counter[i] =0;
}
i++;
});
writeToSlaves();
});
function writeToSlaves(){
//If the previous slave (the slave before the one I am sending to
//in the next step doesnt exist, add the counter or consideer
//it not existing)
if(!slave_exists){
counter[i-1]+=1;
if(counter[i-1]>=countTry){
console.log("--------counter[" + i + "]: " + counter[i]);
// in case that the slave returned no data after trying
//to send him several times
console.log(slaves[i-1] + " doesn't exist");
}
}
//sending to the following slave
b.digitalWrite("P9_17", b.HIGH);
serialPort.write(slaves[i], function(){ slave_exists = false;});
b.digitalWrite("P9_17", b.LOW);
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}
but I am always facing this error:events.js:72
throw er; // Unhandled 'error' event
^
Error: Cannot open /dev/ttyO2
I am running another file first (the code down), the I try to rerun the previous code, and it runs perfect. I need to do that whenever I want to run the first code!
The code that runs from the first time is here:
( I tried the following code alone, it writes to the serial port but doesnt recieve, no event at recieption):
var b = require('bonescript');
var rxport = '/dev/ttyO2';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser: b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
// console.log('tx (' + x.data.length +
// ') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}
The problem was solved.
In /boot/uboot/uEnv.txt, Update the line:"#cape_enable=capemgr.enable_partno= " to be:
"cape_enable=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5 "
or add the last line to the mentioned file. In some cases, you need to try this line instead of the mentioned:
"optargs=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5" (this is my case - but it disabled the HDMI interface of my BBB).
You can specify the UART you want to enable.
A helpful webpage is here.
I'm studying Node.js in college, and it's my first time learning this kind of programming language. I've got some errors in my attempt to build a chat server. When I try to connect one client to the server, the connection closes immediately and I get the error Invalid non-string/buffer chunk. I uploaded a screenshot for you to check out what is wrong, because I've been thinking about it for a while and I can't find any solution.
My Javascript code:
var net = require('net');
var s = require
var sockets = [];
var nombres = [];
var nombresUsados = [];
console.log("Se ha iniciado el sevidor");
var server = net.createServer(function(socket) {
socket.push(socket);
nombres.push("Cliente:" + sockets.indexOf(socket));
nombresUsados.push("Cliente:" + socket.indexOf(socket));
console.log("Cliente aceptado, nick:" + nombres[sockets.indexOf(socket)]);
socket.write("Bienvenido" + nombres[sockets.indexOf(socket)] + "\n");
socket.on('data', function(d) {
var entrada = d.toString();
var UsuarioUnico = entrada.match(/^msg/);
var cambiarNick = entrada.match(/^nick/);
var quit = entrada.match(/^quit/);
if (cambiarNick == "nick") {
var repetido = 0;
var nombresSinNick = entrada.replace(cambiarNick, '');
for (var i = nombres.length - 1; i <= 0; i--) {
if (nombresSinNick.substring(0, nombres[i].toString().length) == nombres[i].toString()) {
socket.write("KO, escoja otro nombre\n")
repetido = 1;
}
};
if (repetido == 0) {
nombres[sockets.indexOf(socket)] == nombresSinNick.trim();
process.on('uncaughtException', function(err) {
socket.write("KO\n");
});
socket.write("OK. " + nombres[sockets.indexOf(socket)] + "\n");
console.log(nombresUsados[sockets.indexOf(socket)]) + "su nombre ha sido cambiado por:" + nombres[sockets.indexOf(socket)];
nombresUsados[sockets.indexOf(socket)] = nombresSinNick.trim();
}
} else if (UsuarioUnico = "msg") {
var nombresSinMsg = entrada.replace(UsuarioUnico, '');
var encontrado = 0;
for (var i = nombres.length - 1; i <= 0; i--) {
if (nombresSinMsg.substring(0, nombres[i].toString().length) == nombres[i].toString()) {
var mensaje = nombresSinMsg.replace(nombres[i], '');
}
};
socket.on('end', function() { // CALLBACK: desconexión de cliente
if (quit == 'quit') {
var i = nombres[sockets.indexOf(socket)];
sockets.splice(i, 1);
console.log("Ha salido el usuario:" + nombres[sockets.indexOf(socket)]);
}
});
}
});
});
server.listen(9000);
I think the problem is the line socket.push(socket). Probably you mean sockets.push(socket). What you're doing now, is attempting to push the socket instance into the socket stream which fails because, as the error says, it's not a string or buffer.
I write some simple app for windows 8 Metro UI with javascript. Because natural method from microsoft to use Sqlite with Javascript in Metro UI. I use 'doo' wrapper:
dooWrapper SQLite (github)
I create a method :
function addSomething(name) {
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\a_db.sqlite';
SQLite3JS.openAsync(dbPath).then(function (db) {
return db.runAsync("INSERT INTO STH (nazwa) VALUES (:name)", { name: name }).
done(function () {
console.log('Add sth : ' + name);
db.close();
}, function (error) {
if (db) {
db.close();
}
console.log('ERROR Adding sth' + error.message);
})
});
}
I get error 'database is locked' I read about this error in documentation. But I have one question is other solution to add more rows without create 'insert' function with collections argument something like that : insert (array) ? I just want to use that function n-times without this error. That's possible?
Yes,it possible...i also got this error before....For that you just need to establish the database connection once...i have used this in my app and its working fine.
If there is no need of closing your db then then open database once like..
Add this code to default.js file
var myDatabase; //Global Variable
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\db.sqlite';
//Create Table
SQLite3JS.openAsync(dbPath).then(function(db) {
myDatabase=db;
return db.runAsync('CREATE TABLE Item (name TEXT, price REAL, id INT PRIMARY KEY)');
});
Then you just need to use below code
// For Insert
return myDatabase.runAsync('INSERT INTO Item (name, price, id) VALUES ("'+ array[i].name+'", "48484", 1);
For array
var dbPromises = [];
var testArray = [];
//only for test purpose
//You can pass your array here directly
for (var a = 0; a < 300; a++) {
var obj = {
name: "Mango"+a,
price: 100+a,
id: a
};
testArray.push(obj);
}
for (var i = 0; i < testArray.length; i++) {
var query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + ')';
dbPromises.push(globalDatabase.allAsync(query));
}
WinJS.Promise.join(dbPromises).then(function () {
debugger;
}, function(err) {
debugger;
});
Above code is used only for less array size...bcz its taking too much time for insertion...
For fasst execution you should replace just below code
for (var i = 0; i < testArray.length; i++) {
var val = '("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + '),';
query = query + val;
if ((i + 1) % 300 == 0 || (i + 1) == testArray.length) {
query = query.replace(/,$/, "");
dbPromises.push(globalDatabase.allAsync(query));
query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ';
}
}