不要怂,就是干,撸起袖子干!

Commit e41a2a67 by Mick Hansen

feat(promises): have hooks.runHooks() return a promise

1 parent 6e754979
......@@ -1224,7 +1224,6 @@ module.exports = (function() {
if (!!err) {
return emitter.emit('error', err)
}
daos = newRecords || daos
options.fields = newFields || options.fields
......
var Utils = require("./utils")
, Promise = require("./promise")
/**
* Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. Hooks can be added to you models in three ways:
......@@ -55,11 +56,11 @@ Hooks.replaceHookAliases = function(hooks) {
}
Hooks.runHooks = function() {
var self = this
, tick = 0
, hooks = arguments[0]
, args = Array.prototype.slice.call(arguments, 1, arguments.length-1)
, fn = arguments[arguments.length-1]
var self = this
, tick = 0
, hooks = arguments[0]
, args = Array.prototype.slice.call(arguments, 1, arguments.length-1)
, fn = arguments[arguments.length-1]
if (typeof hooks === "string") {
hooks = this.options.hooks[hooks] || []
......@@ -69,32 +70,36 @@ Hooks.runHooks = function() {
hooks = hooks === undefined ? [] : [hooks]
}
if (hooks.length < 1) {
return fn.apply(this, [null].concat(args))
}
var run = function(hook) {
if (!hook) {
return fn.apply(this, [null].concat(args))
return new Promise(function (resolve, reject) {
if (hooks.length < 1) {
return resolve(args)
}
if (typeof hook === "object") {
hook = hook.fn
}
hook.apply(self, args.concat(function() {
tick++
var run = function(hook) {
if (!hook) {
return resolve(args)
}
if (!!arguments[0]) {
return fn(arguments[0])
if (typeof hook === "object") {
hook = hook.fn
}
// daoValues = newValues
return run(hooks[tick])
}))
}
hook.apply(self, args.concat(function() {
tick++
if (!!arguments[0]) {
return reject(arguments[0])
}
// daoValues = newValues
return run(hooks[tick])
}))
}
run(hooks[tick])
run(hooks[tick])
}).spread(function () {
fn.apply(self, [null].concat(Array.prototype.slice.apply(arguments)));
}, fn);
}
Hooks.hook = function() {
......
......@@ -173,4 +173,10 @@ SequelizePromise.prototype.proxy = function(promise, options) {
return this
}
SequelizePromise.prototype.proxySql = function(promise) {
return this.proxy(promise, {
events: ['sql']
});
};
module.exports = SequelizePromise;
\ No newline at end of file
......@@ -601,7 +601,7 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
it('should return an error based on the hook', function(done) {
this.User.create({mood: 'happy'}).error(function(err) {
expect(err).to.be.instanceOf(Error);
expect(err.mood[0].message).to.equal( 'Value "ecstatic" for ENUM mood is out of allowed scope. Allowed values: happy, sad, neutral' )
expect(err.mood[0].message).to.equal( 'Value "ecstatic" for ENUM mood is out of allowed scope. Allowed values: happy, sad, neutral' )
done()
})
})
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!