Skip to content

Commit

Permalink
fix: ensure sync errors are thrown, and don't callback twice
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Dec 26, 2019
1 parent 40f5911 commit cca5b49
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 16 deletions.
31 changes: 15 additions & 16 deletions lib/core/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,30 +131,29 @@ function isPromiseLike(maybePromise) {
* @param {function} callback The callback called after every item has been iterated
*/
function eachAsync(arr, eachFn, callback) {
if (arr.length === 0) {
callback(null);
arr = arr || [];

let idx = 0;
let awaiting = 0;
for (idx = 0; idx < arr.length; ++idx) {
awaiting++;
eachFn(arr[idx], eachCallback);
}

if (awaiting === 0) {
callback();
return;
}

const length = arr.length;
let completed = 0;
function eachCallback(err) {
awaiting--;
if (err) {
callback(err, null);
callback(err);
return;
}

if (++completed === length) {
callback(null);
}
}

for (let idx = 0; idx < length; ++idx) {
try {
eachFn(arr[idx], eachCallback);
} catch (err) {
callback(err);
return;
if (idx === arr.length && awaiting <= 0) {
callback();
}
}
}
Expand Down
36 changes: 36 additions & 0 deletions test/unit/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';
const eachAsync = require('../../lib/core/utils').eachAsync;
const expect = require('chai').expect;

describe('utils', function() {
describe('eachAsync', function() {
it('should callback with an error', function(done) {
eachAsync(
[{ error: false }, { error: true }],
(item, cb) => {
cb(item.error ? new Error('error requested') : null);
},
err => {
expect(err).to.exist;
done();
}
);
});

it('should propagate a synchronously thrown error', function(done) {
expect(() =>
eachAsync(
[{}],
() => {
throw new Error('something wicked');
},
err => {
expect(err).to.not.exist;
done(err);
}
)
).to.throw(/something wicked/);
done();
});
});
});

0 comments on commit cca5b49

Please sign in to comment.