我正在开发一个 Web 应用程序,它使用 HTML5/Javascript sqlite 抓取网站 RSS 提要并将其保存到数据库中。
这是我的代码
function createPosts(title,author,content,contentSnippet,publishedDate,img_destaque){
var oldPost = checkIfExists(publishedDate);
console.log(oldPost);
if(!oldPost){
var query = "insert into mytable (titulo, data, autor, img_destaque,descricao,postagem) VALUES (?, ?, ?, ?, ?, ?);";
try {
localDB.transaction(function(transaction){
transaction.executeSql(query, [title, publishedDate, author, img_destaque, contentSnippet, content], function(transaction, results){
if (!results.rowsAffected) {
updateStatus("Error, not data inserted");
}
else {
updateStatus("Data inserted, id: " + results.insertId);
}
}, errorHandler);
});
}
catch (e) {
updateStatus("Error: " + e + ".");
}
}
else{
updateStatus("Error: Post already exists");
}
}
这是函数 checkIfExists
function checkIfExists(publishedDate){
var query = "SELECT * FROM mytable;";
var returnStatus;
try {
localDB.transaction(function(transaction){
transaction.executeSql(query, [], function(transaction, results){
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
if(publishedDate === row.data){
console.log(publishedDate+' '+row.data);
returnStatus = true;
}
}
if(i == results.rows.length){
returnStatus = false;
}
}, function(transaction, result){
returnStatus = true;
}, function(transaction, error){
updateStatus("Erro: " + error.code + "<br>Mensagem: " + error.message);
returnStatus = true;
});
});
}
catch (e) {
updateStatus("Error: SELECT não realizado " + e + ".");
returnStatus = true;
}
finally{
console.log(returnStatus);
return returnStatus;
}
}
但它不起作用 oldPost 总是返回“未定义”,并且通过我的控制台日志记录,我看到 localDB.transaction 在函数返回“oldPost”变量值之后被处理。我该如何解决这个问题?