[英]Returning value inside callback with a Q promise?
在我的代碼中,我從數據庫中獲取hosts
並在回調中對其進行處理。 如何退回已處理的hosts
?
var db = new sqlite3.Database(DB);
var all = Q.nbind(db.all, db);
function getHosts() {
return all('SELECT host FROM hosts ORDER BY host DESC', function(err, rows){
// rows: [ { host: 'z' }, { host: 'a' } ]
// transform into hosts: ['a','z']
var hosts = [];
var L = rows.length;
for (var i=0; i<L; i++) {
hosts.push(rows.pop().host);
}
// hosts = ['a','b', ... 'z']
return hosts; // <-- doesn't work!
});
}
由於要將其轉換為基於promise的函數,因此需要按以下方式使用它:
function getHosts() {
return all('SELECT host FROM hosts ORDER BY host DESC').then(function(rows) {
// rows: [ { host: 'z' }, { host: 'a' } ]
// transform into hosts: ['a','z']
var hosts = [];
var L = rows.length;
for (var i=0; i<L; i++) {
hosts.push(rows.pop().host);
}
// hosts = ['a','b', ... 'z']
return hosts; // <-- doesn't work!
});
}
我這里沒有catch()
處理函數,因此您可以在某個地方處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.