2016-11-23 33 views
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 

回答

1

在node.js的世界裏,你必須明白什麼是異步函數。 如果某個進程需要IO操作,則不能只是從該進程中返回數據,而必須「等待」數據。 我們通常使用回調函數來實現這一點。

這裏的例子給你,

var sqlite3 = require('sqlite3'); 

var dataBaseFile = 'test.db'; 
var dataBase = new sqlite3.Database(dataBaseFile); 

//callback is a function which accept (err, data) 
function returnImagePath(id, callback){ 
    dataBase.serialize(function(){ 
     dataBase.get('SELECT image_path FROM images WHERE id = ' + id, function(error, row){ 
      if (error) { 
       //stop and return error if error occurs 
       return callback(error, null); 
      } 
      image_path = row.image_path; 
      console.log(image_path); //image_path is defined here, and logs as expected 
      //now you get the image path and return it with callback 
      callback(null, image_path); 
      dataBase.close(); 
     }); 
    }); 
} 
returnImagePath(1, function(err, image_path) { 
    if (err) { //capture error(s) 
     return console.error(err); 
    } 
    console.log(image_path); //now you get the image path 
}); 
+0

謝謝。關於爲我學習node.js最困難的事情是瞭解它的異步性。經過幾次閱讀,現在有意義:)。 –