我正在努力了解如何在另一个承诺中解决承诺 我想要实现的步骤如下:
User
(功能)UserManager
个ID
firstName
User
(正常运行)UserManager
保存到数据库
醇>
我希望测试UserManager.saveUser(user);
对成功返回true
的响应。但是我收到了一个错误。
UserManagerTest.js
//[...]
it("Should save a user to the database", function () {
var response = UserManager.getUserByLogin("Foo.Bar@provider.com", "Test")
.then(function (user) {
user.firstName = "Macarena";
return UserManager.saveUser(user);
})
.catch((error) => {
console.log("This error occured: "+error);
return false;
})
return Promise.all([
expect(response).to.eventually.be.true
]);
});
//[...]
控制台输出
1) UserManager Save Should save a user to the database:
AssertionError: expected undefined to be true
at node_modules/chai-as-promised/lib/chai-as-promised.js:305:22
at process._tickCallback (internal/process/next_tick.js:109:7)
UserManager.js
static saveUser(user){
return new Promise((resolve, reject) => {
pool.getConnection((err, connection)=> {
if(err) reject(err);
connection.query("SHOW COLUMNS FROM User;", (error, results, fields) => {
if(error) reject(error);
var availableFields = {savable: [], primary: []};
//[...]
resolve(availableFields);
});
connection.release();
});
})
.then((result) => {
var usedFields = {savable: [], primary: []};
//[...]
return usedFields;
})
.then((result) => {
var sqlParams = [];
var sql = "UPDATE User SET";
//[...]
sql += ";";
pool.getConnection((err, connection) => {
if(err) throw err;
connection.query(sql, sqlParams, (error, results, fields) => {
if(error) throw error;
connection.release();
return results.affectedRows == 1;
});
});
})
.catch((error) => {
console.log(error);
throw error;
})
};
答案 0 :(得分:5)
第二个then((result)=> ...)
不返回任何内容,因此undefined
return results.affectedRows == 1;
位于lambda中。它返回那个lambda,而不是周围的`then``
您需要更改pool.getConnection
的语义,将其从回调更改为Promise。将其包裹在Promise中,解决它并将其链接起来,看起来像
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if(err) {
//see @robertklep comment
try { connection.release(); } catch(e) { /* ignore ? */ }
return reject(err);
}
connection.query(sql, sqlParams, (error, results, fields) => {
if(error) throw error;
connection.release();
resolve(results.affectedRows == 1);
});
});
})
答案 1 :(得分:0)
MySql是异步的,不会返回承诺。
function queryDB(result) {
return new Promise((resolve, reject) => {
var sqlParams = [];
var sql = "UPDATE User SET";
//[...]
sql += ";";
pool.getConnection((err, connection) => {
if(err) {
reject(err);
return connection.release();
}
connection.query(sql, sqlParams, (error, results, fields) => {
if(error) ? reject(error) : resolve(results.affectedRows == 1);
connection.release();
});
});
})
}