mirror of
https://github.com/TryGhost/Ghost.git
synced 2025-02-10 23:36:14 -05:00
Extended sequence utility
no issue - support promise and none promise tasks - helpful if you create an array of operations and not all of the operations/tasks are async - `response instanceof Promise` does not work for all cases e.g. some usages return a transaction/bookshelf chain
This commit is contained in:
parent
c96c474501
commit
27996db5e9
2 changed files with 44 additions and 6 deletions
|
@ -1,16 +1,25 @@
|
||||||
var Promise = require('bluebird');
|
const Promise = require('bluebird');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* expects an array of functions returning a promise
|
* expects an array of functions returning a promise
|
||||||
*/
|
*/
|
||||||
function sequence(tasks /* Any Arguments */) {
|
function sequence(tasks /* Any Arguments */) {
|
||||||
var args = Array.prototype.slice.call(arguments, 1);
|
const args = Array.prototype.slice.call(arguments, 1);
|
||||||
|
|
||||||
return Promise.reduce(tasks, function (results, task) {
|
return Promise.reduce(tasks, function (results, task) {
|
||||||
return task.apply(this, args).then(function (result) {
|
const response = task.apply(this, args);
|
||||||
results.push(result);
|
|
||||||
return results;
|
if (response && response.then) {
|
||||||
});
|
return response.then(function (result) {
|
||||||
|
results.push(result);
|
||||||
|
return results;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return Promise.resolve().then(() => {
|
||||||
|
results.push(response);
|
||||||
|
return results;
|
||||||
|
});
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
29
core/test/unit/lib/promise/sequence_spec.js
Normal file
29
core/test/unit/lib/promise/sequence_spec.js
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
const should = require('should');
|
||||||
|
const sinon = require('sinon');
|
||||||
|
const Promise = require('bluebird');
|
||||||
|
const sequence = require('../../../../server/lib/promise/sequence');
|
||||||
|
const sandbox = sinon.sandbox.create();
|
||||||
|
|
||||||
|
describe('Unit: lib/promise/sequence', function () {
|
||||||
|
afterEach(function () {
|
||||||
|
sandbox.restore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mixed tasks: promise and none promise', function () {
|
||||||
|
const tasks = [
|
||||||
|
function a() {
|
||||||
|
return Promise.resolve('hello');
|
||||||
|
},
|
||||||
|
function b() {
|
||||||
|
return 'from';
|
||||||
|
},
|
||||||
|
function c() {
|
||||||
|
return Promise.resolve('chio');
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return sequence(tasks)
|
||||||
|
.then(function (result) {
|
||||||
|
result.should.eql(['hello','from', 'chio']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
Loading…
Add table
Reference in a new issue