0
問題:我無法使用nodejs庫'sqlite3'中的.get函數將變量放入正確的作用域。無法在npm庫'Sqlite3'中存儲.get方法中的值
說明:儘管我已經宣佈在其從中可以返回出功能,當我爲它分配。獲得方法內的值的範圍的變量「IMAGE_PATH」,IMAGE_PATH的範圍似乎更改;不能再像預期的那樣從函數'returnImagePath'返回。
目標:我只是想創建一個函數,我可以使用nodejs查詢Sqlite3數據庫並返回一個值。如果還有更好的方法來做這個,那麼我現在正在嘗試,我會接受它作爲答案。
例子:
var sqlite3 = require('sqlite3');
var dataBaseFile = 'test.db';
var dataBase = new sqlite3.Database(dataBaseFile);
function returnImagePath(id){
var image_path;
dataBase.serialize(function(){
var statementReturnImagePath = dataBase.prepare(`SELECT image_path FROM images WHERE id = ${id}`);
statementReturnImagePath.run();
statementReturnImagePath.finalize();
dataBase.get(`SELECT image_path FROM images WHERE id = 1`, function(error, row){
image_path = row.image_path;
console.log(image_path); //image_path is defined here, and logs as expected
});
dataBase.close();
});
console.log(image_path); //image_path is undefined here
return image_path;
}
var asdf = returnImagePath(1);
console.log(asdf); //this, therefore doesn't work
謝謝。關於爲我學習node.js最困難的事情是瞭解它的異步性。經過幾次閱讀,現在有意義:)。 –