Q promise .then() undefined
我正在尝试从 MySQL 数据库中异步提取数据,然后使用 Q Promise 处理结果(有史以来第一次尝试)。我正在使用此处列出的 Q defer() 函数。我创建了一个 "wrapper" 对象,我最终将附加到 req.db 或通过来自 com.db 的循环依赖项访问(当前使用方式),以允许在我的应用程序中使用 api。
节点抛出指向 .then 回调的错误:
1 2 3 | this.go().then(function(stuff){ ^ TypeError: Cannot call method 'then' of undefined |
我尝试了以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | var com = require('./mainRebuild'); function Base() { this.results = []; this.query = 'query here'; this.go = function() { com.pool.getConnection(function(err, con) { if (err) throw err; /* THIS WORKS FINE (with callbacks) con.query('SELECT * FROM Users', function(err, rows){ if (err) throw err; if (rows){ for (var i = 0; i < rows.length; i++){ this.results.push(rows[i]); //console.log(rows[i]); } } con.release(); return this.results; }.bind(this)); */ var defer = com.Q.defer(); con.query('SELECT * FROM Users', defer.makeNodeResolver()); return defer.promise(); }.bind(this)); } } function DB() { this.getAllUsers = function() { this.query = 'SELECT * FROM Users'; this.go().then(function(stuff) { console.log(stuff); }, function(err) { console.log(err); }); } } DB.prototype = new Base(); module.exports = DB; |
com 对象存在于主应用程序中,它包含所有常见的 require 模块。
我也试过了(好像错多了):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | this.deffered = com.Q.defer(); com.pool.getConnection(function(err, con) { if (err) this.deferred.reject(new Error(err)); con.query('SELECT * FROM Users', function(err, rows) { if (err) throw err; if (rows) { this.deferred.resolve(rows); } con.release(); return this.deferred.promise.done; }.bind(this)); com.Q.nfcall(this.go()).then... |
我找到了几篇关于像这样将 Q 适配到节点的文章。
应该这样做("应该",因为我无法用 MySQL 测试它)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | var Q = require('Q'); function DB(pool) { this.asyncQuery = function(sql) { return function () { var result = Q.defer(), paramsArray = [].slice.call(arguments); pool.getConnection(function(err, con) { if (err) return result.thenReject(err); con.query(sql, paramsArray, result.makeNodeResolver()); result.promise.finally(function () { con.release(); }); }); return result.promise; }; }; this.getAllUsers = this.asyncQuery('SELECT * FROM Users'); this.getUserByName = this.asyncQuery('SELECT * FROM Users WHERE name = ?'); } module.exports = DB; |
用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var DB = require('./DB'); var com = require('./mainRebuild'); var db = new DB(com.pool); db.getAllUsers().then(function (users) { console.log(users); }); db.getUserByName('JohnDoe').then(function (user) { console.log(user); }); var customQuery = db.asyncQuery('SELECT * FROM foo WHERE id = ?'); customQuery(42).then(function (result) { console.log(result); }); |