diff options
author | Alexander Early <alexander.early@gmail.com> | 2018-09-03 00:02:21 -0700 |
---|---|---|
committer | Alexander Early <alexander.early@gmail.com> | 2018-09-03 00:02:21 -0700 |
commit | 105fd5d2bd08dbd5c3f29a695b76a18cb159f0d7 (patch) | |
tree | 506d535c67ca15a6469355412b71a5eae5658ef4 | |
parent | 4dbafbafe1747ed0952bac91f58d36f56e8f0c52 (diff) | |
download | async-105fd5d2bd08dbd5c3f29a695b76a18cb159f0d7.tar.gz |
awaitable tryEach
-rw-r--r-- | lib/tryEach.js | 8 | ||||
-rw-r--r-- | test/es2017/awaitableFunctions.js | 12 |
2 files changed, 18 insertions, 2 deletions
diff --git a/lib/tryEach.js b/lib/tryEach.js index af885dc..98ecbd4 100644 --- a/lib/tryEach.js +++ b/lib/tryEach.js @@ -1,6 +1,7 @@ import eachSeries from './eachSeries'; import noop from './internal/noop'; import wrapAsync from './internal/wrapAsync'; +import awaitify from './internal/awaitify' /** * It runs each task in series but stops whenever any of the functions were @@ -21,6 +22,7 @@ import wrapAsync from './internal/wrapAsync'; * of the tasks has succeeded, or all have failed. It receives the `err` and * `result` arguments of the last attempt at completing the `task`. Invoked with * (err, results). + * @returns {Promise} a promise, if no callback is passed * @example * async.tryEach([ * function getDataFromFirstWebsite(callback) { @@ -39,11 +41,11 @@ import wrapAsync from './internal/wrapAsync'; * }); * */ -export default function tryEach(tasks, callback) { +function tryEach(tasks, callback) { var error = null; var result; callback = callback || noop; - eachSeries(tasks, (task, taskCb) => { + return eachSeries(tasks, (task, taskCb) => { wrapAsync(task)((err, ...args) => { if (args.length < 2) { [result] = args; @@ -55,3 +57,5 @@ export default function tryEach(tasks, callback) { }); }, () => callback(error, result)); } + +export default awaitify(tryEach) diff --git a/test/es2017/awaitableFunctions.js b/test/es2017/awaitableFunctions.js index 9db61a2..b0b3bda 100644 --- a/test/es2017/awaitableFunctions.js +++ b/test/es2017/awaitableFunctions.js @@ -546,4 +546,16 @@ module.exports = function () { }) expect(calls).to.eql([0, 1, 2]) }); + + it('should return a Promise: tryEach', async () => { + expect (async.tryEach.name).to.contain('tryEach') + const calls = [] + await async.tryEach([ + async () => { await Promise.resolve(); calls.push(1); throw new Error() }, + async () => { await Promise.resolve(); calls.push(2); throw new Error() }, + async () => { await Promise.resolve(); calls.push(3) }, + async () => { await Promise.resolve(); calls.push(4) }, + ], 2) + expect(calls).to.eql([1, 2, 3]) + }); }; |