2017-02-12 81 views
0

我正在爲具有電子模塊的node.js使用sqlite3模塊。我是JavaScript的新手,我正在努力回調和異步代碼。如何將SQLite結果傳遞給Nodejs中的回調

我的目的是讓getTable函數運行,構建表數組並將該數組傳遞給useTable函數的回調函數。

所以這個功能應該建立並通過表數組:

function getTable(callback) { 
    const sqlite3 = require('sqlite3').verbose(); 
    var testDatabase = new sqlite3.Database('app/data/testDatabase.db'); 
    var table = []; 
    var testRow = []; 
    testDatabase.each("SELECT * FROM test_Accounts", function(err, row) { 
     testRow.push(row.test_id); 
     testRow.push(row.test_creation_date); 
     testRow.push(row.domain); 
     testRow.push(row.test_login_url); 
     table.push(testRow); 
     testRow = []; 
    }); 
    testDatabase.close(); 
    callback(table); 
} 

而這個功能將採取表數組並使用它:

function useTable(table) { 
    //code that uses the table array passed to this function from the getTable function. 
} 

,我會跑這個是這樣的:

getTable(useTable); 

當我運行這個時,控制檯顯示沒有錯誤。看起來useTable函數在getTable函數中完成table數組之前運行,我認爲這是回調的主要目的之一,在獲取該數組之前等待異步代碼運行(在此情況下爲構建數組),並將它傳遞給另一個函數。

如何確保getTable函數中的table數組在完成生成之後才能通過並運行useTable函數?

回答

1

您應該使用testDatabase.all函數一次獲取所有行。例如:

testDatabase.all('SELECT * from test_accounts',callback) 

請參閱文檔:

使用指定的參數SQL查詢,並呼籲所有結果行之後的回調。 https://github.com/mapbox/node-sqlite3/wiki/API#databaseallsql-param--callback

還要說明一點:在的NodeJS,當你調用回調則建議使用第一個返回值nullerror值的函數。

function useTable(err,table){ 
    if (err){ 
    throw Err 
    } 
    else { 
    // Do something with the data 
    } 
} 

getTable(useTable) 
相關問題