![](/img/trans.png)
[英]How to persist data through promise chain in NodeJS (Bluebird)
[英]how to implement bluebird promise in nodejs
我嘗試了節點藍鳥的承諾,我無法在當時的函數中使用resolve&reject。 下面是我的代碼,它叫做promise
modules.modelClip.exGetAllClips(sUserData)
.then(function(finalResult) {
console.log("Final result " + finalResult)
})
.error(function(e) {
console.log("Error handler " + e)
})
.catch(function(e) {
console.log("Catch handler " + e)
});
並且在exGetAllClips函數中返回promise。
exports.exGetAllClips = function(pUserData) {
console.log("--- inside : clipModel : exGetAllClips -----------------------------------------------------");
console.log(pUserData);
return new modules.promise(function(resolve, reject) {
modules.dbConnection.getConnection(function(rErrorCon, connection) {
if (rErrorCon) {
reject(rErrorCon);
} else {
resolve(connection);
}
});
}).then(function(connection) {
console.log('Result 4 ')
var sClipQuery = "CALL spGetAllClips(?)";
var query = connection.query(sClipQuery, [pUserData.selfId
]);
query.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
//return err;
console.log(" error : spGetAllClips : ",err);
reject(err);
}).on('result', function(row) {
console.log("row : ", JSON.stringify(row));
resolve( row);
}).on('end', function() {
// all rows have been received
connection.release();
})
});
};
如果存在.then
我想從.then
拋出錯誤。 但是不能做到這一點,它拋出錯誤拒絕是undefined
。
請幫忙,如何實現這個或任何其他方式。
我想這樣,首先有兩個回調(一個實際上是一個eventHandler,我不太習慣使用Promises來處理它),所以將它們分成兩個promise:
通過promisifying整個模塊使用getConnectionAsync
而不是getConnection
。
按照bluebird docs處理一次性事件(請注意,我沒有維護一個標志來檢查promise是否已經解決),代碼可能是這樣的:
modules.dbConnection = modules.promise.promisifyAll(modules.dbConnection); ... exports.exGetAllClips = function(pUserData) { console.log("--- inside : clipModel : exGetAllClips -----------------------------------------------------"); console.log(pUserData); return modules.dbConnection.getConnectionAsync() .then(function(connection) { console.log('Result 4 ') var sClipQuery = "CALL spGetAllClips(?)"; return new modules.promise(function(resolve, reject){ var query = connection.query(sClipQuery, [pUserData.selfId]); query.on('error', function(err) { // Handle error, an 'end' event will be emitted after this as well //return err; console.log(" error : spGetAllClips : ",err); reject(err); }).on('result', function(row) { console.log("row : ", JSON.stringify(row)); resolve( row); }).on('end', function() { // all rows have been received connection.release(); }); }); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.