- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
一直在尝试 promisify node-mysql2 事务,但无法让它工作,有什么指示吗?
我已经阅读了 http://bluebirdjs.com/docs/api/disposer.html 上的文档
我也有非交易相关代码的工作版本,但是让交易正常工作,以及适当的资源处置和错误处理一直很困难。这是从 node-mysql api 文档中获取的基于回调的实现
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
var log = 'Post ' + result.insertId + ' added';
connection.query('INSERT INTO log SET data=?', log, function(err, result) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
connection.commit(function(err) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
console.log('success!');
});
});
});
});
这是我对查询管理的实现
import { mysqldb } from '../config';
import { createPool } from 'mysql2';
import Pool from 'mysql2/lib/pool';
import Connection from 'mysql2/lib/connection';
import { using, promisifyAll, try as promiseTry } from 'bluebird';
promisifyAll([Pool, Connection]);
const pool = createPool(mysqldb);
export const getConnection = () =>
pool.getConnectionAsync().disposer(connection =>
connection.release());
export const withTransaction = (fn) =>
using(getConnection(), tx =>
promiseTry(fn(tx), tx.beginTransaction()).then(
res => tx.commitAsync().catch(e => e).thenReturn(res),
err => tx.rollbackAsync().catch(e => e).thenThrow(err)
)
);
// withTransaction(tx =>
// tx.executeAsync('sql1')
// .then(tx.executeAsync('sql2'))
// .then(tx.executeAsync('sql3'))
// .then(tx.executeAsync('sql4'))
// );
export const query = (sql, params) =>
using(getConnection(), connection =>
connection.executeAsync(sql, params)
);
然而交易给了我
Unhandled rejection TypeError: expecting a function but got [object Object]
at apiRejection (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:10:27)
at Promise.attempt.Promise.try (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/method.js:26:16)
at /Users/willh/workspace/ChenPin/graphql/lib/services/mysql.js:35:30
at tryCatcher (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/util.js:16:23)
at /Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/using.js:184:26
at tryCatcher (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:503:31)
at Promise._settlePromise (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:560:18)
at Promise._settlePromise0 (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:605:10)
at Promise._settlePromises (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:684:18)
at Promise._fulfill (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:629:18)
at PromiseArray._resolve (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise_array.js:125:19)
at PromiseArray._promiseFulfilled (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise_array.js:143:14)
at Promise._settlePromise (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:565:26)
at Promise._settlePromise0 (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:605:10)
at Promise._settlePromises (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:684:18)
at Promise._fulfill (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:629:18)
at Promise._resolveCallback (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:424:57)
at Promise._settlePromiseFromHandler (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:515:17)
at Promise._settlePromise (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:560:18)
at Promise._settlePromise0 (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:605:10)
at Promise._settlePromises (/Users/willh/workspace/ChenPin/graphql/node_modules/bluebird/js/release/promise.js:684:18)
什么是正确的方法?
更新:
通过查看源代码让它工作,结果发现它只是一个简单的助手,真的不值得使用他们的助手,下面是最终的工作版本。无论如何感谢您的帮助:D
export const withTransaction = (fn) =>
using(getConnection(), tx =>
tx.queryAsync('START TRANSACTION').then(fn(tx)).then(
res => tx.queryAsync('COMMIT').thenReturn(res),
err => tx.queryAsync('ROLLBACK').catch(e => e).thenThrow(err)
)
);
// withTransaction(tx =>
// tx.executeAsync('select :x + :y as z', { x: 1, y: 2 }).then(res1 =>
// tx.executeAsync('select :x + :y as z', { x: res1[0].z, y: 1 })).then(res2 =>
// tx.executeAsync('select :x + :y as z', { x: res2[0].z, y: 1 })).then(res3 =>
// tx.executeAsync('select :x + :y as z', { x: res3[0].z, y: 1 })).then(res4 => res4)
// );
顺便说一句,原来的 promisify 方法是有效的,没有什么区别,但感谢您帮助我!
最佳答案
您遇到错误是因为 promisifyAll
使用的是函数而不是对象。在大多数情况下,函数存在于类的 prototype
中。试试这个
var Promise = require('bluebird');
var mysql = require('mysql2');
Promise.promisifyAll(mysql.Connection.prototype);
Promise.promisifyAll(require('mysql2/lib/pool').prototype)
在我上面的练习示例中,效果很好。
如果你觉得你想在这个领域做更多的实验,你也可以手动遍历所有元素并只选择函数,就像我个人在 Postgres 中使用的下面的例子
var Promise = require('bluebird');
var pg = require('pg');
Object.keys(pg).forEach(function (key) {
var Cls = null;
try {
Cls = pg[key];
if (typeof Cls === 'function') {
Promise.promisifyAll(Cls.prototype);
Promise.promisifyAll(Cls);
}
} catch (e) {
console.log(e);
}
});
Promise.promisifyAll(pg);
关于transactions - bluebird node-mysql2事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758045/
bluebird.js和bluebird.core.js有什么区别? 什么时候应该使用bluebird.core.js而不是bluebird.js? 我无法在bluebird site或其他地方找到任
我正在从异步转换为 Bluebird,但不知道如何打破循环 这是我想要实现的目标: 循环数据数组。 对于每个项目,检查它是否存在于数据库中。 将一个项添加到数据库(第一个不存在的项),然后退出.eac
我试图用 .try(function(){}).catch(function(){}) 块返回一个 promise 。我的问题是由我的 promise 类型引起的。 deleteProcess
我正在尝试使用 bluebird 的 .return() 来扩展 promise 解析值方法。 目前我正在使用以下代码: doSomethingAsync() // assu
我刚刚开始使用 Promise 和 Bluebird。调试时我可以看到我的函数执行了两次: 首先我收到此错误:TypeError:未捕获错误:无法读取未定义的属性“then” 然后我看到函数再次执行,
我想测试数组的每个元素,直到满足条件,然后跳过其余的。这是我想出的代码,它似乎有效,但我不确定它是否真的安全或有意想不到的副作用。欢迎其他解决方案。 let buddyAdded = false; r
假设我有以下 node.js 代码 function foo() { return promiseOne().then(function(result) { return pr
假设我想在从数据库查找用户后同时发送电子邮件并向客户端推送通知,我可以这样写 User.findById(userId).exec() .then(() => sendMail()) .then(()
.call 方法的 Bluebird 文档有 code sample标记为“链接破折号或下划线方法”。 下面的代码片段中链接的 .then(_) 的用途是什么? var Promise = requi
是否有某种方法可以检索从上一个 then 回调返回的任何内容(或传递给初始 Promise.resolve()/resolve())? const p = Bluebird.resolve().the
我有以下代码。当 f2 没有抛出错误时,它工作正常。 如果有错误,它会生成一个Unhandled rejection Error。 重写代码以避免 Unhandled rejection Error
我有一个来自这篇文章的后续问题:Chaining Requests using BlueBird/ Request-Promise 我对 promise 很陌生,所以请原谅我的天真。我成功地实现了这段
我是 Bluebird 的新手,我正在尝试创建一个新用户,但 reject 函数没有按预期工作。 问题是它为我创建了用户,即使它启动了错误There nickname is already in us
我正在尝试实现剪刀石头布游戏的 CLI 版本。我正在使用查询器模块来处理 IO。我的主要功能如下所示: RockPaperScissors.prototype.gameLoop = function(
此代码运行正常: let promise; try { promise = parent(); //but I want: await parent(); await cont
在 promise 了 fs-extra 后,我知道我可以使用 then 来访问文件。我猜想有某种机制,在获取文件后,它知道要移动到 then 链中的下一个链接。然而,接下来的then我只是放置了一个
我有以下代码。它按预期工作,没有抛出未处理的拒绝错误。 p = new Promise (fulfill, reject) -> reject new Error 'some error' p.c
我期待 Bluebird forgotten return warning出现,但由于某种原因它不起作用。 A demo : const Bluebird = require('bluebird');
我正在使用 bluebird图书馆结束memcached . memcached.set('foo', 'bar', 10, function (err) { /* stuff */ }); 此函数不
我正在尝试如下使用 Bluebird 的协程: var p = require('bluebird'); //this should return a promise resolved to valu
我是一名优秀的程序员,十分优秀!