Skip to content

Commit

Permalink
Events are triggered sequentially when the handlers execute async code
Browse files Browse the repository at this point in the history
closes #1765

- `triggerThen` was running in parallel before
  - event handlers were executed at the same time
  - that means you can't rely on an operation (or a change) which a previous handler executed
- use `mapSeries` instead
- added a test
  • Loading branch information
kirrg001 committed Mar 13, 2018
1 parent b04ef8d commit dabce13
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/base/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export default class Events extends EventEmitter {
triggerThen(nameOrNames, ...args) {
const names = eventNames(nameOrNames);
const listeners = flatMap(names, name => this.listeners(name));
return Promise.map(listeners, listener => listener.apply(this, args));
return Promise.mapSeries(listeners, listener => listener.apply(this, args));
}

/**
Expand Down
24 changes: 24 additions & 0 deletions test/integration/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,30 @@ module.exports = function(bookshelf) {
});
});

it('ensure events are triggered sequentially when the handlers do async stuff', function() {
var m = new Site({name: 'new'});

m.on('saving', function(model) {
return new Promise(function (resolve) {
setTimeout(function () {
model.set('x', 'y');
resolve();
}, 200);
});
});

m.on('saving', function(model) {
equal(model.get('x'), 'y');
model.unset('x');
m.off();
});

return m.save(null, {method: 'insert'})
.then(function () {
return m.destroy();
});
});

it('updates an existing object', function() {
return new Site({id: 4, name: 'Fourth Site Updated'}).save()
.then(function() {
Expand Down

0 comments on commit dabce13

Please sign in to comment.