From 8b3c9050051119bcba5384738c5f34792852b06c Mon Sep 17 00:00:00 2001 From: Roman Balayan Date: Mon, 5 Oct 2020 13:03:11 +0800 Subject: [PATCH 1/3] Enhance examples for Collections methods. --- docs/v3/concat.js.html | 72 +- docs/v3/detect.js.html | 45 +- docs/v3/docs.html | 1174 +++++++++++++++++++++++++++---- docs/v3/each.js.html | 89 ++- docs/v3/eachOf.js.html | 87 ++- docs/v3/every.js.html | 77 +- docs/v3/filter.js.html | 52 +- docs/v3/groupBy.js.html | 68 +- docs/v3/groupBySeries.js.html | 2 +- docs/v3/map.js.html | 84 ++- docs/v3/mapValues.js.html | 112 ++- docs/v3/module-Collections.html | 1170 ++++++++++++++++++++++++++---- docs/v3/module-ControlFlow.html | 4 +- docs/v3/queue.js.html | 2 +- docs/v3/reduce.js.html | 88 ++- docs/v3/reject.js.html | 48 +- docs/v3/some.js.html | 78 +- docs/v3/sortBy.js.html | 134 +++- docs/v3/transform.js.html | 122 +++- docs/v3/until.js.html | 2 +- lib/concat.js | 72 +- lib/detect.js | 45 +- lib/each.js | 89 ++- lib/eachOf.js | 87 ++- lib/every.js | 77 +- lib/filter.js | 52 +- lib/groupBy.js | 68 +- lib/map.js | 84 ++- lib/mapValues.js | 112 ++- lib/reduce.js | 88 ++- lib/reject.js | 48 +- lib/some.js | 78 +- lib/sortBy.js | 134 +++- lib/transform.js | 122 +++- package-lock.json | 2 +- 35 files changed, 4144 insertions(+), 524 deletions(-) diff --git a/docs/v3/concat.js.html b/docs/v3/concat.js.html index 023a089c5..9bc898478 100644 --- a/docs/v3/concat.js.html +++ b/docs/v3/concat.js.html @@ -100,9 +100,77 @@

concat.js

* @returns A Promise, if no callback is passed * @example * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * })(); + * */ function concat(coll, iteratee, callback) { return concatLimit(coll, Infinity, iteratee, callback) diff --git a/docs/v3/detect.js.html b/docs/v3/detect.js.html index fe6d4c953..f67e375a1 100644 --- a/docs/v3/detect.js.html +++ b/docs/v3/detect.js.html @@ -107,13 +107,48 @@

detect.js

* @returns A Promise, if no callback is passed * @example * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function detect(coll, iteratee, callback) { return createTester(bool => bool, (res, item) => item)(eachOf, coll, iteratee, callback) diff --git a/docs/v3/docs.html b/docs/v3/docs.html index 5655ab247..252bcdf46 100644 --- a/docs/v3/docs.html +++ b/docs/v3/docs.html @@ -484,9 +484,76 @@
Returns:
Example
-
async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
-    // files is now a list of filenames that exist in the 3 directories
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+let directoryList = ['dir1','dir2','dir3'];
+let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
+
+// Using callbacks
+async.concat(directoryList, fs.readdir, function(err, results) {
+   if (err) {
+       console.log(err);
+   } else {
+       console.log(results);
+       // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+   }
+});
+
+// Error Handling
+async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
+   if (err) {
+       console.log(err);
+       // [ Error: ENOENT: no such file or directory ]
+       // since dir4 does not exist
+   } else {
+       console.log(results);
+   }
+});
+
+// Using Promises
+async.concat(directoryList, fs.readdir)
+.then(results => {
+    console.log(results);
+    // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+}).catch(err => {
+     console.log(err);
+});
+
+// Error Handling
+async.concat(withMissingDirectoryList, fs.readdir)
+.then(results => {
+    console.log(results);
+}).catch(err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4 does not exist
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.concat(directoryList, fs.readdir);
+        console.log(results);
+        // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+    } catch (err) {
+        console.log(err);
+    }
+})();
+
+// Error Handling
+(async () => {
+    try {
+        let results = await async.concat(withMissingDirectoryList, fs.readdir);
+        console.log(results);
+    } catch (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+        // since dir4 does not exist
+    }
+})();
@@ -1167,13 +1234,47 @@
Returns:
Example
-
async.detect(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // dir1/file1.txt
+       // result now equals the first file in the list that exists
+   }
+);
+
+// Using Promises
+async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
+.then(result => {
+    console.log(result);
+    // dir1/file1.txt
     // result now equals the first file in the list that exists
-});
+}).catch(err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + console.log(result); + // dir1/file1.txt + // result now equals the file in the list that exists + } + catch (err) { + console.log(err); + } +})();
@@ -1868,37 +1969,77 @@
Returns:
Example
-
// assuming openFiles is an array of file names and saveFile is a function
-// to save the modified contents of that file:
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
+const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
+
+// asynchronous function that deletes a file
+const deleteFile = function(file, callback) {
+    fs.unlink(file, callback);
+};
+
+// Using callbacks
+async.each(fileList, deleteFile, function(err) {
+    if( err ) {
+        console.log(err);
+    } else {
+        console.log('All files have been deleted successfully');
+    }
+});
 
-async.each(openFiles, saveFile, function(err){
-  // if any of the saves produced an error, err would equal that error
+// Error Handling
+async.each(withMissingFileList, deleteFile, function(err){
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4/file2.txt does not exist
+    // dir1/file1.txt could have been deleted
 });
 
-// assuming openFiles is an array of file names
-async.each(openFiles, function(file, callback) {
+// Using Promises
+async.each(fileList, deleteFile)
+.then( () => {
+    console.log('All files have been deleted successfully');
+}).catch( err => {
+    console.log(err);
+});
 
-    // Perform operation on file here.
-    console.log('Processing file ' + file);
+// Error Handling
+async.each(fileList, deleteFile)
+.then( () => {
+    console.log('All files have been deleted successfully');
+}).catch( err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4/file2.txt does not exist
+    // dir1/file1.txt could have been deleted
+});
 
-    if( file.length > 32 ) {
-      console.log('This file name is too long');
-      callback('File name too long');
-    } else {
-      // Do work to process file here
-      console.log('File processed');
-      callback();
+// Using async/await
+(async () => {
+    try {
+        await async.each(files, deleteFile);
     }
-}, function(err) {
-    // if any of the file processing produced an error, err would equal that error
-    if( err ) {
-      // One of the iterations produced an error.
-      // All processing will now stop.
-      console.log('A file failed to process');
-    } else {
-      console.log('All files have been processed successfully');
+    catch (err) {
+        console.log(err);
     }
-});
+})(); + +// Error Handling +(async () => { + try { + await async.each(withMissingFileList, deleteFile); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + // since dir4/file2.txt does not exist + // dir1/file1.txt could have been deleted + } +})();
@@ -2379,12 +2520,19 @@
Returns:
Example
-
var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
-var configs = {};
+    
// dev.json is a file containing a valid json object config for dev environment
+// dev.json is a file containing a valid json object config for test environment
+// prod.json is a file containing a valid json object config for prod environment
+// invalid.json is a file with a malformed json object
 
-async.forEachOf(obj, function (value, key, callback) {
-    fs.readFile(__dirname + value, "utf8", function (err, data) {
-        if (err) return callback(err);
+let configs = {}; //global variable
+let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
+let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
+
+// asynchronous function that reads a json file and parses the contents as json object
+function parseFile(file, key, callback) {
+    fs.readFile(file, "utf8", function(err, data) {
+        if (err) return calback(err);
         try {
             configs[key] = JSON.parse(data);
         } catch (e) {
@@ -2392,11 +2540,72 @@ 
Example
} callback(); }); -}, function (err) { - if (err) console.error(err.message); - // configs is now a map of JSON data - doSomethingWith(configs); -});
+} + +// Using callbacks +async.forEachOf(validConfigFileMap, parseFile, function (err) { + if (err) { + console.error(err); + } else { + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + } +}); + +//Error handing +async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + if (err) { + console.error(err); + // JSON parse error exception + } else { + console.log(configs); + } +}); + +// Using Promises +async.forEachOf(validConfigFileMap, parseFile) +.then( () => { + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} +}).catch( err => { + console.error(err); +}); + +//Error handing +async.forEachOf(invalidConfigFileMap, parseFile) +.then( () => { + console.log(configs); +}).catch( err => { + console.error(err); + // JSON parse error exception +}); + +// Using async/await +(async () => { + try { + let result = await async.forEachOf(validConfigFileMap, parseFile); + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + } + catch (err) { + console.log(err); + } +})(); + +//Error handing +(async () => { + try { + let result = await async.forEachOf(invalidConfigFileMap, parseFile); + console.log(configs); + } + catch (err) { + console.log(err); + // JSON parse error exception + } +})();
@@ -3345,13 +3554,77 @@
Returns:
Example
-
async.every(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
-    // if result is true then every file exists
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.every(fileList, fileExists, function(err, result) {
+    console.log(result);
+    // true
+    // result is true since every file exists
+});
+
+async.every(withMissingFileList, fileExists, function(err, result) {
+    console.log(result);
+    // false
+    // result is false since NOT every file exists
+});
+
+// Using Promises
+async.every(fileList, fileExists)
+.then( result => {
+    console.log(result);
+    // true
+    // result is true since every file exists
+}).catch( err => {
+    console.log(err);
+});
+
+async.every(withMissingFileList, fileExists)
+.then( result => {
+    console.log(result);
+    // false
+    // result is false since NOT every file exists
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.every(fileList, fileExists);
+        console.log(result);
+        // true
+        // result is true since every file exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+(async () => {
+    try {
+        let result = await async.every(withMissingFileList, fileExists);
+        console.log(result);
+        // false
+        // result is false since NOT every file exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -4062,13 +4335,52 @@
Returns:
Example
-
async.filter(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, results) {
-    // results now equals an array of the existing files
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.filter(files, fileExists, function(err, results) {
+   if(err) {
+       console.log(err);
+   } else {
+       console.log(results);
+       // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+       // results is now an array of the existing files
+   }
+});
+
+// Using Promises
+async.filter(files, fileExists)
+.then(results => {
+    console.log(results);
+    // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+    // results is now an array of the existing files
+}).catch(err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.filter(files, fileExists);
+        console.log(results);
+        // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+        // results is now an array of the existing files
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -4778,15 +5090,68 @@
Returns:
Example
-
async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
-    db.findById(userId, function(err, user) {
-        if (err) return callback(err);
-        return callback(null, user.age);
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const files = ['dir1/file1.txt','dir2','dir4']
+
+// asynchronous function that detects file type as none, file, or directory
+function detectFile(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(null, 'none');
+        }
+        callback(null, stat.isDirectory() ? 'directory' : 'file');
     });
-}, function(err, result) {
-    // result is object containing the userIds grouped by age
-    // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
-});
+} + +//Using callbacks +async.groupBy(files, detectFile, function(err, result) { + if(err) { + console.log(err); + } else { + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type + } +}); + +// Using Promises +async.groupBy(files, detectFile) +.then( result => { + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type +}).catch( err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.groupBy(files, detectFile); + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type + } + catch (err) { + console.log(err); + } +})();
@@ -5220,7 +5585,7 @@
Parameters:

A callback which is called when all iteratee -functions have finished, or an error occurs. Result is an Object whoses +functions have finished, or an error occurs. Result is an Object whose properties are arrays of values which returned the corresponding key.

@@ -5494,9 +5859,88 @@
Returns:
Example
-
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
-    // results is now an array of stats for each file
-});
+
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
+    });
+}
+
+// Using callbacks
+async.map(fileList, getFileSizeInBytes, function(err, results) {
+    if (err) {
+        console.log(err);
+    } else {
+        console.log(results);
+        // results is now an array of the file size in bytes for each file, e.g.
+        // [ 1000, 2000, 3000]
+    }
+});
+
+// Error Handling
+async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
+    if (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    } else {
+        console.log(results);
+    }
+});
+
+// Using Promises
+async.map(fileList, getFileSizeInBytes)
+.then( results => {
+    console.log(results);
+    // results is now an array of the file size in bytes for each file, e.g.
+    // [ 1000, 2000, 3000]
+}).catch( err => {
+    console.log(err);
+});
+
+// Error Handling
+async.map(withMissingFileList, getFileSizeInBytes)
+.then( results => {
+    console.log(results);
+}).catch( err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.map(fileList, getFileSizeInBytes);
+        console.log(results);
+        // results is now an array of the file size in bytes for each file, e.g.
+        // [ 1000, 2000, 3000]
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+// Error Handling
+(async () => {
+    try {
+        let results = await async.map(withMissingFileList, getFileSizeInBytes);
+        console.log(results);
+    }
+    catch (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    }
+})();
@@ -6192,20 +6636,109 @@
Returns:
Example
-
async.mapValues({
-    f1: 'file1',
-    f2: 'file2',
-    f3: 'file3'
-}, function (file, key, callback) {
-  fs.stat(file, callback);
-}, function(err, result) {
-    // result is now a map of stats for each file, e.g.
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileMap = {
+    f1: 'file1.txt',
+    f2: 'file2.txt',
+    f3: 'file3.txt'
+};
+
+const withMissingFileMap = {
+    f1: 'file1.txt',
+    f2: 'file2.txt',
+    f3: 'file4.txt'
+};
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, key, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
+    });
+}
+
+// Using callbacks
+async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {
+    if (err) {
+        console.log(err);
+    } else {
+        console.log(result);
+        // result is now a map of file size in bytes for each file, e.g.
+        // {
+        //     f1: 1000,
+        //     f2: 2000,
+        //     f3: 3000
+        // }
+    }
+});
+
+// Error handling
+async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {
+    if (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    } else {
+        console.log(result);
+    }
+});
+
+// Using Promises
+async.mapValues(fileMap, getFileSizeInBytes)
+.then( result => {
+    console.log(result);
+    // result is now a map of file size in bytes for each file, e.g.
     // {
-    //     f1: [stats for file1],
-    //     f2: [stats for file2],
-    //     f3: [stats for file3]
+    //     f1: 1000,
+    //     f2: 2000,
+    //     f3: 3000
     // }
-});
+}).catch (err => { + console.log(err); +}); + +// Error Handling +async.mapValues(withMissingFileMap, getFileSizeInBytes) +.then( result => { + console.log(result); +}).catch (err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let result = await async.mapValues(fileMap, getFileSizeInBytes); + console.log(result); + // result is now a map of file size in bytes for each file, e.g. + // { + // f1: 1000, + // f2: 2000, + // f3: 3000 + // } + } + catch (err) { + console.log(err); + } +})(); + +// Error Handling +(async () => { + try { + let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + console.log(result); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -6923,14 +7456,89 @@
Returns:
Example
-
async.reduce([1,2,3], 0, function(memo, item, callback) {
-    // pointless async:
-    process.nextTick(function() {
-        callback(null, memo + item)
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
+
+// asynchronous function that computes the file size in bytes
+// file size is added to the memoized value, then returned
+function getFileSizeInBytes(memo, file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, memo + stat.size);
     });
-}, function(err, result) {
-    // result is now equal to the last value of memo, which is 6
-});
+} + +// Using callbacks +async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + if (err) { + console.log(err); + } else { + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files + } +}); + +// Error Handling +async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + if (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } else { + console.log(result); + } +}); + +// Using Promises +async.reduce(fileList, 0, getFileSizeInBytes) +.then( result => { + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files +}).catch( err => { + console.log(err); +}); + +// Error Handling +async.reduce(withMissingFileList, 0, getFileSizeInBytes) +.then( result => { + console.log(result); +}).catch( err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let result = await async.reduce(fileList, 0, getFileSizeInBytes); + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files + } + catch (err) { + console.log(err); + } +})(); + +// Error Handling +(async () => { + try { + let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + console.log(result); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -7398,14 +8006,47 @@
Returns:
Example
-
async.reject(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, results) {
-    // results now equals an array of missing files
-    createFiles(results);
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.reject(fileList, fileExists, function(err, results) {
+   // [ 'dir3/file6.txt' ]
+   // results now equals an array of the non-existing files
+});
+
+// Using Promises
+async.reject(fileList, fileExists)
+.then( results => {
+    console.log(results);
+    // [ 'dir3/file6.txt' ]
+    // results now equals an array of the non-existing files
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.reject(fileList, fileExists);
+        console.log(results);
+        // [ 'dir3/file6.txt' ]
+        // results now equals an array of the non-existing files
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -8115,13 +8756,78 @@
Returns:
Example
-
async.some(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
-    // if result is true then at least one of the files exists
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // true
+       // result is true since some file in the list exists
+   }
+);
+
+async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // false
+       // result is false since none of the files exists
+   }
+);
+
+// Using Promises
+async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
+.then( result => {
+    console.log(result);
+    // true
+    // result is true since some file in the list exists
+}).catch( err => {
+    console.log(err);
+});
+
+async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
+.then( result => {
+    console.log(result);
+    // false
+    // result is false since none of the files exists
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
+        console.log(result);
+        // true
+        // result is true since some file in the list exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+(async () => {
+    try {
+        let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
+        console.log(result);
+        // false
+        // result is false since none of the files exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -8830,31 +9536,132 @@
Returns:
Example
-
async.sortBy(['file1','file2','file3'], function(file, callback) {
-    fs.stat(file, function(err, stats) {
-        callback(err, stats.mtime);
+    
// bigfile.txt is a file that is 251100 bytes in size
+// mediumfile.txt is a file that is 11000 bytes in size
+// smallfile.txt is a file that is 121 bytes in size
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
     });
-}, function(err, results) {
-    // results is now the original array of files sorted by
-    // modified date
-});
+}
+
+// Using callbacks
+async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
+    function(err, results) {
+        if (err) {
+            console.log(err);
+        } else {
+            console.log(results);
+            // results is now the original array of files sorted by
+            // file size (ascending by default), e.g.
+            // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
+        }
+    }
+);
 
 // By modifying the callback parameter the
 // sorting order can be influenced:
 
 // ascending order
-async.sortBy([1,9,3,5], function(x, callback) {
-    callback(null, x);
-}, function(err,result) {
-    // result callback
-});
+async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
+    getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
+        if (getFileSizeErr) return callback(getFileSizeErr);
+        callback(null, fileSize);
+    });
+}, function(err, results) {
+        if (err) {
+            console.log(err);
+        } else {
+            console.log(results);
+            // results is now the original array of files sorted by
+            // file size (ascending by default), e.g.
+            // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
+        }
+    }
+);
 
 // descending order
-async.sortBy([1,9,3,5], function(x, callback) {
-    callback(null, x*-1);    //<- x*-1 instead of x, turns the order around
-}, function(err,result) {
-    // result callback
-});
+async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + if (getFileSizeErr) { + return callback(getFileSizeErr); + } + callback(null, fileSize * -1); + }); +}, function(err, results) { + if (err) { + console.log(err); + } else { + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + } + } +); + +// Error handling +async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + function(err, results) { + if (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } else { + console.log(results); + } + } +); + +// Using Promises +async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) +.then( results => { + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] +}).catch( err => { + console.log(err); +}); + +// Error handling +async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) +.then( results => { + console.log(results); +}).catch( err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + } + catch (err) { + console.log(err); + } +})(); + +// Error handling +(async () => { + try { + let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + console.log(results); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -9104,24 +9911,115 @@
Returns:
Examples
-
async.transform([1,2,3], function(acc, item, index, callback) {
-    // pointless async:
-    process.nextTick(function() {
-        acc[index] = item * 2
-        callback(null)
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+
+// helper function that returns human-readable size format from bytes
+function formatBytes(bytes, decimals = 2) {
+  // implementation not included for brevity
+  return humanReadbleFilesize;
+}
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+
+// asynchronous function that returns the file size, transformed to human-readable format
+// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
+function transformFileSize(acc, value, key, callback) {
+    fs.stat(value, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        acc[key] = formatBytes(stat.size);
+        callback(null);
     });
-}, function(err, result) {
-    // result is now equal to [2, 4, 6]
-});
+} -
async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
-    setImmediate(function () {
-        obj[key] = val * 2;
-        callback();
-    })
-}, function (err, result) {
-    // result is equal to {a: 2, b: 4, c: 6}
-})
+// Using callbacks +async.transform(fileList, transformFileSize, function(err, result) { + if(err) { + console.log(err); + } else { + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + } +}); + +// Using Promises +async.transform(fileList, transformFileSize) +.then(result => { + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] +}).catch(err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.transform(fileList, transformFileSize); + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + } + catch (err) { + console.log(err); + } +})();
+ +
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+
+// helper function that returns human-readable size format from bytes
+function formatBytes(bytes, decimals = 2) {
+  // implementation not included for brevity
+  return humanReadbleFilesize;
+}
+
+const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };
+
+// asynchronous function that returns the file size, transformed to human-readable format
+// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
+function transformFileSize(acc, value, key, callback) {
+    fs.stat(value, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        acc[key] = formatBytes(stat.size);
+        callback(null);
+    });
+}
+
+// Using callbacks
+async.transform(fileMap, transformFileSize, function(err, result) {
+    if(err) {
+        console.log(err);
+    } else {
+        console.log(result);
+        // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+    }
+});
+
+// Using Promises
+async.transform(fileMap, transformFileSize)
+.then(result => {
+    console.log(result);
+    // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+}).catch(err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.transform(fileMap, transformFileSize);
+        console.log(result);
+        // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -14781,7 +15679,7 @@
Example
const results = []
 let finished = false
-async.until(function test(page, cb) {
+async.until(function test(cb) {
     cb(null, finished)
 }, function iter(next) {
     fetchPage(url, (err, body) => {
@@ -15605,7 +16503,7 @@ 
Properties:
- unshirtAsync + unshiftAsync diff --git a/docs/v3/each.js.html b/docs/v3/each.js.html index d7b7cd8e3..02b4a4688 100644 --- a/docs/v3/each.js.html +++ b/docs/v3/each.js.html @@ -106,37 +106,78 @@

each.js

* @returns {Promise} a promise, if a callback is omitted * @example * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; * - * // Perform operation on file here. - * console.log('Processing file ' + file); + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); + * console.log(err); * } else { - * console.log('All files have been processed successfully'); + * console.log('All files have been deleted successfully'); * } * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * (async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * })(); + * */ function eachLimit(coll, iteratee, callback) { return eachOf(coll, withoutIndex(wrapAsync(iteratee)), callback); diff --git a/docs/v3/eachOf.js.html b/docs/v3/eachOf.js.html index 70bacd2da..a130440d0 100644 --- a/docs/v3/eachOf.js.html +++ b/docs/v3/eachOf.js.html @@ -137,12 +137,19 @@

eachOf.js

* @returns {Promise} a promise, if a callback is omitted * @example * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); * try { * configs[key] = JSON.parse(data); * } catch (e) { @@ -150,11 +157,73 @@

eachOf.js

* } * callback(); * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * //Error handing + * (async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * })(); + * */ function eachOf(coll, iteratee, callback) { var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; diff --git a/docs/v3/every.js.html b/docs/v3/every.js.html index a57e5ebd3..f2f885e5a 100644 --- a/docs/v3/every.js.html +++ b/docs/v3/every.js.html @@ -100,13 +100,78 @@

every.js

* @returns {Promise} a promise, if no callback provided * @example * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * (async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function every(coll, iteratee, callback) { return createTester(bool => !bool, res => !res)(eachOf, coll, iteratee, callback) diff --git a/docs/v3/filter.js.html b/docs/v3/filter.js.html index 5dc2b0523..0ebaa1afd 100644 --- a/docs/v3/filter.js.html +++ b/docs/v3/filter.js.html @@ -99,13 +99,53 @@

filter.js

* @returns {Promise} a promise, if no callback provided * @example * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function filter (coll, iteratee, callback) { return _filter(eachOf, coll, iteratee, callback) diff --git a/docs/v3/groupBy.js.html b/docs/v3/groupBy.js.html index 52ee786d2..a2b895614 100644 --- a/docs/v3/groupBy.js.html +++ b/docs/v3/groupBy.js.html @@ -104,15 +104,69 @@

groupBy.js

* @returns {Promise} a promise, if no callback is passed * @example * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ export default function groupBy (coll, iteratee, callback) { return groupByLimit(coll, Infinity, iteratee, callback) diff --git a/docs/v3/groupBySeries.js.html b/docs/v3/groupBySeries.js.html index 7ee5c7845..65e18f6c0 100644 --- a/docs/v3/groupBySeries.js.html +++ b/docs/v3/groupBySeries.js.html @@ -92,7 +92,7 @@

groupBySeries.js

* The iteratee should complete with a `key` to group the value under. * Invoked with (value, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses + * functions have finished, or an error occurs. Result is an `Object` whose * properties are arrays of values which returned the corresponding key. * @returns {Promise} a promise, if no callback is passed */ diff --git a/docs/v3/map.js.html b/docs/v3/map.js.html index dc5dd005a..3b4cd0a17 100644 --- a/docs/v3/map.js.html +++ b/docs/v3/map.js.html @@ -112,9 +112,89 @@

map.js

* @returns {Promise} a promise, if no callback is passed * @example * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function map (coll, iteratee, callback) { return _map(eachOf, coll, iteratee, callback) diff --git a/docs/v3/mapValues.js.html b/docs/v3/mapValues.js.html index d86c326a9..58988be55 100644 --- a/docs/v3/mapValues.js.html +++ b/docs/v3/mapValues.js.html @@ -107,20 +107,110 @@

mapValues.js

* @returns {Promise} a promise, if no callback is passed * @example * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ export default function mapValues(obj, iteratee, callback) { return mapValuesLimit(obj, Infinity, iteratee, callback) diff --git a/docs/v3/module-Collections.html b/docs/v3/module-Collections.html index a38a08958..b74f70914 100644 --- a/docs/v3/module-Collections.html +++ b/docs/v3/module-Collections.html @@ -344,9 +344,76 @@
Returns:
Example
-
async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
-    // files is now a list of filenames that exist in the 3 directories
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+let directoryList = ['dir1','dir2','dir3'];
+let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
+
+// Using callbacks
+async.concat(directoryList, fs.readdir, function(err, results) {
+   if (err) {
+       console.log(err);
+   } else {
+       console.log(results);
+       // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+   }
+});
+
+// Error Handling
+async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
+   if (err) {
+       console.log(err);
+       // [ Error: ENOENT: no such file or directory ]
+       // since dir4 does not exist
+   } else {
+       console.log(results);
+   }
+});
+
+// Using Promises
+async.concat(directoryList, fs.readdir)
+.then(results => {
+    console.log(results);
+    // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+}).catch(err => {
+     console.log(err);
+});
+
+// Error Handling
+async.concat(withMissingDirectoryList, fs.readdir)
+.then(results => {
+    console.log(results);
+}).catch(err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4 does not exist
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.concat(directoryList, fs.readdir);
+        console.log(results);
+        // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
+    } catch (err) {
+        console.log(err);
+    }
+})();
+
+// Error Handling
+(async () => {
+    try {
+        let results = await async.concat(withMissingDirectoryList, fs.readdir);
+        console.log(results);
+    } catch (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+        // since dir4 does not exist
+    }
+})();
@@ -1027,13 +1094,47 @@
Returns:
Example
-
async.detect(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // dir1/file1.txt
+       // result now equals the first file in the list that exists
+   }
+);
+
+// Using Promises
+async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
+.then(result => {
+    console.log(result);
+    // dir1/file1.txt
     // result now equals the first file in the list that exists
-});
+}).catch(err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + console.log(result); + // dir1/file1.txt + // result now equals the file in the list that exists + } + catch (err) { + console.log(err); + } +})();
@@ -1728,37 +1829,77 @@
Returns:
Example
-
// assuming openFiles is an array of file names and saveFile is a function
-// to save the modified contents of that file:
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
+const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
+
+// asynchronous function that deletes a file
+const deleteFile = function(file, callback) {
+    fs.unlink(file, callback);
+};
+
+// Using callbacks
+async.each(fileList, deleteFile, function(err) {
+    if( err ) {
+        console.log(err);
+    } else {
+        console.log('All files have been deleted successfully');
+    }
+});
 
-async.each(openFiles, saveFile, function(err){
-  // if any of the saves produced an error, err would equal that error
+// Error Handling
+async.each(withMissingFileList, deleteFile, function(err){
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4/file2.txt does not exist
+    // dir1/file1.txt could have been deleted
 });
 
-// assuming openFiles is an array of file names
-async.each(openFiles, function(file, callback) {
+// Using Promises
+async.each(fileList, deleteFile)
+.then( () => {
+    console.log('All files have been deleted successfully');
+}).catch( err => {
+    console.log(err);
+});
 
-    // Perform operation on file here.
-    console.log('Processing file ' + file);
+// Error Handling
+async.each(fileList, deleteFile)
+.then( () => {
+    console.log('All files have been deleted successfully');
+}).catch( err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+    // since dir4/file2.txt does not exist
+    // dir1/file1.txt could have been deleted
+});
 
-    if( file.length > 32 ) {
-      console.log('This file name is too long');
-      callback('File name too long');
-    } else {
-      // Do work to process file here
-      console.log('File processed');
-      callback();
+// Using async/await
+(async () => {
+    try {
+        await async.each(files, deleteFile);
     }
-}, function(err) {
-    // if any of the file processing produced an error, err would equal that error
-    if( err ) {
-      // One of the iterations produced an error.
-      // All processing will now stop.
-      console.log('A file failed to process');
-    } else {
-      console.log('All files have been processed successfully');
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+// Error Handling
+(async () => {
+    try {
+        await async.each(withMissingFileList, deleteFile);
+    }
+    catch (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+        // since dir4/file2.txt does not exist
+        // dir1/file1.txt could have been deleted
     }
-});
+})();
@@ -2239,12 +2380,19 @@
Returns:
Example
-
var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
-var configs = {};
+    
// dev.json is a file containing a valid json object config for dev environment
+// dev.json is a file containing a valid json object config for test environment
+// prod.json is a file containing a valid json object config for prod environment
+// invalid.json is a file with a malformed json object
 
-async.forEachOf(obj, function (value, key, callback) {
-    fs.readFile(__dirname + value, "utf8", function (err, data) {
-        if (err) return callback(err);
+let configs = {}; //global variable
+let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
+let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
+
+// asynchronous function that reads a json file and parses the contents as json object
+function parseFile(file, key, callback) {
+    fs.readFile(file, "utf8", function(err, data) {
+        if (err) return calback(err);
         try {
             configs[key] = JSON.parse(data);
         } catch (e) {
@@ -2252,11 +2400,72 @@ 
Example
} callback(); }); -}, function (err) { - if (err) console.error(err.message); - // configs is now a map of JSON data - doSomethingWith(configs); -});
+} + +// Using callbacks +async.forEachOf(validConfigFileMap, parseFile, function (err) { + if (err) { + console.error(err); + } else { + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + } +}); + +//Error handing +async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + if (err) { + console.error(err); + // JSON parse error exception + } else { + console.log(configs); + } +}); + +// Using Promises +async.forEachOf(validConfigFileMap, parseFile) +.then( () => { + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} +}).catch( err => { + console.error(err); +}); + +//Error handing +async.forEachOf(invalidConfigFileMap, parseFile) +.then( () => { + console.log(configs); +}).catch( err => { + console.error(err); + // JSON parse error exception +}); + +// Using async/await +(async () => { + try { + let result = await async.forEachOf(validConfigFileMap, parseFile); + console.log(configs); + // configs is now a map of JSON data, e.g. + // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + } + catch (err) { + console.log(err); + } +})(); + +//Error handing +(async () => { + try { + let result = await async.forEachOf(invalidConfigFileMap, parseFile); + console.log(configs); + } + catch (err) { + console.log(err); + // JSON parse error exception + } +})();
@@ -3205,13 +3414,77 @@
Returns:
Example
-
async.every(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
-    // if result is true then every file exists
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.every(fileList, fileExists, function(err, result) {
+    console.log(result);
+    // true
+    // result is true since every file exists
+});
+
+async.every(withMissingFileList, fileExists, function(err, result) {
+    console.log(result);
+    // false
+    // result is false since NOT every file exists
+});
+
+// Using Promises
+async.every(fileList, fileExists)
+.then( result => {
+    console.log(result);
+    // true
+    // result is true since every file exists
+}).catch( err => {
+    console.log(err);
+});
+
+async.every(withMissingFileList, fileExists)
+.then( result => {
+    console.log(result);
+    // false
+    // result is false since NOT every file exists
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.every(fileList, fileExists);
+        console.log(result);
+        // true
+        // result is true since every file exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+(async () => {
+    try {
+        let result = await async.every(withMissingFileList, fileExists);
+        console.log(result);
+        // false
+        // result is false since NOT every file exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -3922,13 +4195,52 @@
Returns:
Example
-
async.filter(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, results) {
-    // results now equals an array of the existing files
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.filter(files, fileExists, function(err, results) {
+   if(err) {
+       console.log(err);
+   } else {
+       console.log(results);
+       // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+       // results is now an array of the existing files
+   }
+});
+
+// Using Promises
+async.filter(files, fileExists)
+.then(results => {
+    console.log(results);
+    // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+    // results is now an array of the existing files
+}).catch(err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.filter(files, fileExists);
+        console.log(results);
+        // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
+        // results is now an array of the existing files
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -4638,15 +4950,68 @@
Returns:
Example
-
async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
-    db.findById(userId, function(err, user) {
-        if (err) return callback(err);
-        return callback(null, user.age);
+    
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+const files = ['dir1/file1.txt','dir2','dir4']
+
+// asynchronous function that detects file type as none, file, or directory
+function detectFile(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(null, 'none');
+        }
+        callback(null, stat.isDirectory() ? 'directory' : 'file');
     });
-}, function(err, result) {
-    // result is object containing the userIds grouped by age
-    // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
-});
+} + +//Using callbacks +async.groupBy(files, detectFile, function(err, result) { + if(err) { + console.log(err); + } else { + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type + } +}); + +// Using Promises +async.groupBy(files, detectFile) +.then( result => { + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type +}).catch( err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.groupBy(files, detectFile); + console.log(result); + // { + // file: [ 'dir1/file1.txt' ], + // none: [ 'dir4' ], + // directory: [ 'dir2'] + // } + // result is object containing the files grouped by type + } + catch (err) { + console.log(err); + } +})();
@@ -5080,7 +5445,7 @@
Parameters:

A callback which is called when all iteratee -functions have finished, or an error occurs. Result is an Object whoses +functions have finished, or an error occurs. Result is an Object whose properties are arrays of values which returned the corresponding key.

@@ -5354,9 +5719,88 @@
Returns:
Example
-
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
-    // results is now an array of stats for each file
-});
+
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
+    });
+}
+
+// Using callbacks
+async.map(fileList, getFileSizeInBytes, function(err, results) {
+    if (err) {
+        console.log(err);
+    } else {
+        console.log(results);
+        // results is now an array of the file size in bytes for each file, e.g.
+        // [ 1000, 2000, 3000]
+    }
+});
+
+// Error Handling
+async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
+    if (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    } else {
+        console.log(results);
+    }
+});
+
+// Using Promises
+async.map(fileList, getFileSizeInBytes)
+.then( results => {
+    console.log(results);
+    // results is now an array of the file size in bytes for each file, e.g.
+    // [ 1000, 2000, 3000]
+}).catch( err => {
+    console.log(err);
+});
+
+// Error Handling
+async.map(withMissingFileList, getFileSizeInBytes)
+.then( results => {
+    console.log(results);
+}).catch( err => {
+    console.log(err);
+    // [ Error: ENOENT: no such file or directory ]
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.map(fileList, getFileSizeInBytes);
+        console.log(results);
+        // results is now an array of the file size in bytes for each file, e.g.
+        // [ 1000, 2000, 3000]
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+// Error Handling
+(async () => {
+    try {
+        let results = await async.map(withMissingFileList, getFileSizeInBytes);
+        console.log(results);
+    }
+    catch (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    }
+})();
@@ -6052,20 +6496,109 @@
Returns:
Example
-
async.mapValues({
-    f1: 'file1',
-    f2: 'file2',
-    f3: 'file3'
-}, function (file, key, callback) {
-  fs.stat(file, callback);
-}, function(err, result) {
-    // result is now a map of stats for each file, e.g.
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileMap = {
+    f1: 'file1.txt',
+    f2: 'file2.txt',
+    f3: 'file3.txt'
+};
+
+const withMissingFileMap = {
+    f1: 'file1.txt',
+    f2: 'file2.txt',
+    f3: 'file4.txt'
+};
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, key, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
+    });
+}
+
+// Using callbacks
+async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {
+    if (err) {
+        console.log(err);
+    } else {
+        console.log(result);
+        // result is now a map of file size in bytes for each file, e.g.
+        // {
+        //     f1: 1000,
+        //     f2: 2000,
+        //     f3: 3000
+        // }
+    }
+});
+
+// Error handling
+async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {
+    if (err) {
+        console.log(err);
+        // [ Error: ENOENT: no such file or directory ]
+    } else {
+        console.log(result);
+    }
+});
+
+// Using Promises
+async.mapValues(fileMap, getFileSizeInBytes)
+.then( result => {
+    console.log(result);
+    // result is now a map of file size in bytes for each file, e.g.
     // {
-    //     f1: [stats for file1],
-    //     f2: [stats for file2],
-    //     f3: [stats for file3]
+    //     f1: 1000,
+    //     f2: 2000,
+    //     f3: 3000
     // }
-});
+}).catch (err => { + console.log(err); +}); + +// Error Handling +async.mapValues(withMissingFileMap, getFileSizeInBytes) +.then( result => { + console.log(result); +}).catch (err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let result = await async.mapValues(fileMap, getFileSizeInBytes); + console.log(result); + // result is now a map of file size in bytes for each file, e.g. + // { + // f1: 1000, + // f2: 2000, + // f3: 3000 + // } + } + catch (err) { + console.log(err); + } +})(); + +// Error Handling +(async () => { + try { + let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + console.log(result); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -6783,14 +7316,89 @@
Returns:
Example
-
async.reduce([1,2,3], 0, function(memo, item, callback) {
-    // pointless async:
-    process.nextTick(function() {
-        callback(null, memo + item)
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+// file4.txt does not exist
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
+
+// asynchronous function that computes the file size in bytes
+// file size is added to the memoized value, then returned
+function getFileSizeInBytes(memo, file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, memo + stat.size);
     });
-}, function(err, result) {
-    // result is now equal to the last value of memo, which is 6
-});
+} + +// Using callbacks +async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + if (err) { + console.log(err); + } else { + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files + } +}); + +// Error Handling +async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + if (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } else { + console.log(result); + } +}); + +// Using Promises +async.reduce(fileList, 0, getFileSizeInBytes) +.then( result => { + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files +}).catch( err => { + console.log(err); +}); + +// Error Handling +async.reduce(withMissingFileList, 0, getFileSizeInBytes) +.then( result => { + console.log(result); +}).catch( err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let result = await async.reduce(fileList, 0, getFileSizeInBytes); + console.log(result); + // 6000 + // which is the sum of the file sizes of the three files + } + catch (err) { + console.log(err); + } +})(); + +// Error Handling +(async () => { + try { + let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + console.log(result); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -7258,14 +7866,47 @@
Returns:
Example
-
async.reject(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, results) {
-    // results now equals an array of missing files
-    createFiles(results);
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+
+const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.reject(fileList, fileExists, function(err, results) {
+   // [ 'dir3/file6.txt' ]
+   // results now equals an array of the non-existing files
+});
+
+// Using Promises
+async.reject(fileList, fileExists)
+.then( results => {
+    console.log(results);
+    // [ 'dir3/file6.txt' ]
+    // results now equals an array of the non-existing files
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let results = await async.reject(fileList, fileExists);
+        console.log(results);
+        // [ 'dir3/file6.txt' ]
+        // results now equals an array of the non-existing files
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -7975,13 +8616,78 @@
Returns:
Example
-
async.some(['file1','file2','file3'], function(filePath, callback) {
-    fs.access(filePath, function(err) {
-        callback(null, !err)
-    });
-}, function(err, result) {
-    // if result is true then at least one of the files exists
-});
+
// dir1 is a directory that contains file1.txt, file2.txt
+// dir2 is a directory that contains file3.txt, file4.txt
+// dir3 is a directory that contains file5.txt
+// dir4 does not exist
+
+// asynchronous function that checks if a file exists
+function fileExists(file, callback) {
+   fs.access(file, fs.constants.F_OK, (err) => {
+       callback(null, !err);
+   });
+}
+
+// Using callbacks
+async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // true
+       // result is true since some file in the list exists
+   }
+);
+
+async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
+   function(err, result) {
+       console.log(result);
+       // false
+       // result is false since none of the files exists
+   }
+);
+
+// Using Promises
+async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
+.then( result => {
+    console.log(result);
+    // true
+    // result is true since some file in the list exists
+}).catch( err => {
+    console.log(err);
+});
+
+async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
+.then( result => {
+    console.log(result);
+    // false
+    // result is false since none of the files exists
+}).catch( err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
+        console.log(result);
+        // true
+        // result is true since some file in the list exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
+
+(async () => {
+    try {
+        let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
+        console.log(result);
+        // false
+        // result is false since none of the files exists
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
@@ -8690,31 +9396,132 @@
Returns:
Example
-
async.sortBy(['file1','file2','file3'], function(file, callback) {
-    fs.stat(file, function(err, stats) {
-        callback(err, stats.mtime);
+    
// bigfile.txt is a file that is 251100 bytes in size
+// mediumfile.txt is a file that is 11000 bytes in size
+// smallfile.txt is a file that is 121 bytes in size
+
+// asynchronous function that returns the file size in bytes
+function getFileSizeInBytes(file, callback) {
+    fs.stat(file, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        callback(null, stat.size);
     });
-}, function(err, results) {
-    // results is now the original array of files sorted by
-    // modified date
-});
+}
+
+// Using callbacks
+async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
+    function(err, results) {
+        if (err) {
+            console.log(err);
+        } else {
+            console.log(results);
+            // results is now the original array of files sorted by
+            // file size (ascending by default), e.g.
+            // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
+        }
+    }
+);
 
 // By modifying the callback parameter the
 // sorting order can be influenced:
 
 // ascending order
-async.sortBy([1,9,3,5], function(x, callback) {
-    callback(null, x);
-}, function(err,result) {
-    // result callback
-});
+async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
+    getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
+        if (getFileSizeErr) return callback(getFileSizeErr);
+        callback(null, fileSize);
+    });
+}, function(err, results) {
+        if (err) {
+            console.log(err);
+        } else {
+            console.log(results);
+            // results is now the original array of files sorted by
+            // file size (ascending by default), e.g.
+            // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
+        }
+    }
+);
 
 // descending order
-async.sortBy([1,9,3,5], function(x, callback) {
-    callback(null, x*-1);    //<- x*-1 instead of x, turns the order around
-}, function(err,result) {
-    // result callback
-});
+async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + if (getFileSizeErr) { + return callback(getFileSizeErr); + } + callback(null, fileSize * -1); + }); +}, function(err, results) { + if (err) { + console.log(err); + } else { + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + } + } +); + +// Error handling +async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + function(err, results) { + if (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } else { + console.log(results); + } + } +); + +// Using Promises +async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) +.then( results => { + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] +}).catch( err => { + console.log(err); +}); + +// Error handling +async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) +.then( results => { + console.log(results); +}).catch( err => { + console.log(err); + // [ Error: ENOENT: no such file or directory ] +}); + +// Using async/await +(async () => { + try { + let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + console.log(results); + // results is now the original array of files sorted by + // file size (ascending by default), e.g. + // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + } + catch (err) { + console.log(err); + } +})(); + +// Error handling +(async () => { + try { + let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + console.log(results); + } + catch (err) { + console.log(err); + // [ Error: ENOENT: no such file or directory ] + } +})();
@@ -8964,24 +9771,115 @@
Returns:
Examples
-
async.transform([1,2,3], function(acc, item, index, callback) {
-    // pointless async:
-    process.nextTick(function() {
-        acc[index] = item * 2
-        callback(null)
+    
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+
+// helper function that returns human-readable size format from bytes
+function formatBytes(bytes, decimals = 2) {
+  // implementation not included for brevity
+  return humanReadbleFilesize;
+}
+
+const fileList = ['file1.txt','file2.txt','file3.txt'];
+
+// asynchronous function that returns the file size, transformed to human-readable format
+// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
+function transformFileSize(acc, value, key, callback) {
+    fs.stat(value, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        acc[key] = formatBytes(stat.size);
+        callback(null);
     });
-}, function(err, result) {
-    // result is now equal to [2, 4, 6]
-});
+} -
async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
-    setImmediate(function () {
-        obj[key] = val * 2;
-        callback();
-    })
-}, function (err, result) {
-    // result is equal to {a: 2, b: 4, c: 6}
-})
+// Using callbacks +async.transform(fileList, transformFileSize, function(err, result) { + if(err) { + console.log(err); + } else { + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + } +}); + +// Using Promises +async.transform(fileList, transformFileSize) +.then(result => { + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] +}).catch(err => { + console.log(err); +}); + +// Using async/await +(async () => { + try { + let result = await async.transform(fileList, transformFileSize); + console.log(result); + // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + } + catch (err) { + console.log(err); + } +})();
+ +
// file1.txt is a file that is 1000 bytes in size
+// file2.txt is a file that is 2000 bytes in size
+// file3.txt is a file that is 3000 bytes in size
+
+// helper function that returns human-readable size format from bytes
+function formatBytes(bytes, decimals = 2) {
+  // implementation not included for brevity
+  return humanReadbleFilesize;
+}
+
+const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };
+
+// asynchronous function that returns the file size, transformed to human-readable format
+// e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
+function transformFileSize(acc, value, key, callback) {
+    fs.stat(value, function(err, stat) {
+        if (err) {
+            return callback(err);
+        }
+        acc[key] = formatBytes(stat.size);
+        callback(null);
+    });
+}
+
+// Using callbacks
+async.transform(fileMap, transformFileSize, function(err, result) {
+    if(err) {
+        console.log(err);
+    } else {
+        console.log(result);
+        // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+    }
+});
+
+// Using Promises
+async.transform(fileMap, transformFileSize)
+.then(result => {
+    console.log(result);
+    // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+}).catch(err => {
+    console.log(err);
+});
+
+// Using async/await
+(async () => {
+    try {
+        let result = await async.transform(fileMap, transformFileSize);
+        console.log(result);
+        // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
+    }
+    catch (err) {
+        console.log(err);
+    }
+})();
diff --git a/docs/v3/module-ControlFlow.html b/docs/v3/module-ControlFlow.html index fb16cd328..472aeb83b 100644 --- a/docs/v3/module-ControlFlow.html +++ b/docs/v3/module-ControlFlow.html @@ -5652,7 +5652,7 @@
Example
const results = []
 let finished = false
-async.until(function test(page, cb) {
+async.until(function test(cb) {
     cb(null, finished)
 }, function iter(next) {
     fetchPage(url, (err, body) => {
@@ -6476,7 +6476,7 @@ 
Properties:
- unshirtAsync + unshiftAsync diff --git a/docs/v3/queue.js.html b/docs/v3/queue.js.html index b213ef527..d4d00de4f 100644 --- a/docs/v3/queue.js.html +++ b/docs/v3/queue.js.html @@ -106,7 +106,7 @@

queue.js

* Invoke with `queue.unshift(task, [callback])`. * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns * a promise that rejects if an error occurs. - * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns * a promise that rejects if an error occurs. * @property {Function} remove - remove items from the queue that match a test * function. The test function will be passed an object with a `data` property, diff --git a/docs/v3/reduce.js.html b/docs/v3/reduce.js.html index e85a14e8b..260b64f5d 100644 --- a/docs/v3/reduce.js.html +++ b/docs/v3/reduce.js.html @@ -112,14 +112,90 @@

reduce.js

* @returns {Promise} a promise, if no callback is passed * @example * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function reduce(coll, memo, iteratee, callback) { callback = once(callback); diff --git a/docs/v3/reject.js.html b/docs/v3/reject.js.html index ddad8436d..eeb3b50d6 100644 --- a/docs/v3/reject.js.html +++ b/docs/v3/reject.js.html @@ -98,14 +98,48 @@

reject.js

* @returns {Promise} a promise, if no callback is passed * @example * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function reject (coll, iteratee, callback) { return _reject(eachOf, coll, iteratee, callback) diff --git a/docs/v3/some.js.html b/docs/v3/some.js.html index a4f8579ba..e6b03c5a1 100644 --- a/docs/v3/some.js.html +++ b/docs/v3/some.js.html @@ -102,13 +102,79 @@

some.js

* @returns {Promise} a promise, if no callback provided * @example * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * (async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function some(coll, iteratee, callback) { return createTester(Boolean, res => res)(eachOf, coll, iteratee, callback) diff --git a/docs/v3/sortBy.js.html b/docs/v3/sortBy.js.html index 4198f8556..840916724 100644 --- a/docs/v3/sortBy.js.html +++ b/docs/v3/sortBy.js.html @@ -101,31 +101,133 @@

sortBy.js

* @returns {Promise} a promise, if no callback passed * @example * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); * * // By modifying the callback parameter the * // sorting order can be influenced: * * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); * * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * (async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); diff --git a/docs/v3/transform.js.html b/docs/v3/transform.js.html index 2bce88e7a..ab73bc033 100644 --- a/docs/v3/transform.js.html +++ b/docs/v3/transform.js.html @@ -102,26 +102,118 @@

transform.js

* @returns {Promise} a promise, if no callback provided * @example * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc[index] = item * 2 - * callback(null) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } * }); * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * * @example * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ export default function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3 && typeof accumulator === 'function') { diff --git a/docs/v3/until.js.html b/docs/v3/until.js.html index 6b5a2720b..5cb8c52b1 100644 --- a/docs/v3/until.js.html +++ b/docs/v3/until.js.html @@ -104,7 +104,7 @@

until.js

* @example * const results = [] * let finished = false - * async.until(function test(page, cb) { + * async.until(function test(cb) { * cb(null, finished) * }, function iter(next) { * fetchPage(url, (err, body) => { diff --git a/lib/concat.js b/lib/concat.js index c6dc11c31..37561c143 100644 --- a/lib/concat.js +++ b/lib/concat.js @@ -23,9 +23,77 @@ import awaitify from './internal/awaitify' * @returns A Promise, if no callback is passed * @example * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * })(); + * */ function concat(coll, iteratee, callback) { return concatLimit(coll, Infinity, iteratee, callback) diff --git a/lib/detect.js b/lib/detect.js index 4a6746a5d..d70e8c00c 100644 --- a/lib/detect.js +++ b/lib/detect.js @@ -30,13 +30,48 @@ import awaitify from './internal/awaitify' * @returns A Promise, if no callback is passed * @example * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function detect(coll, iteratee, callback) { return createTester(bool => bool, (res, item) => item)(eachOf, coll, iteratee, callback) diff --git a/lib/each.js b/lib/each.js index 7f6e689c5..ea0798b16 100644 --- a/lib/each.js +++ b/lib/each.js @@ -29,37 +29,78 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if a callback is omitted * @example * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; * - * // Perform operation on file here. - * console.log('Processing file ' + file); + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); + * console.log(err); * } else { - * console.log('All files have been processed successfully'); + * console.log('All files have been deleted successfully'); * } * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * (async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * })(); + * */ function eachLimit(coll, iteratee, callback) { return eachOf(coll, withoutIndex(wrapAsync(iteratee)), callback); diff --git a/lib/eachOf.js b/lib/eachOf.js index 0b847aec9..5c655b212 100644 --- a/lib/eachOf.js +++ b/lib/eachOf.js @@ -60,12 +60,19 @@ function eachOfGeneric (coll, iteratee, callback) { * @returns {Promise} a promise, if a callback is omitted * @example * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); * try { * configs[key] = JSON.parse(data); * } catch (e) { @@ -73,11 +80,73 @@ function eachOfGeneric (coll, iteratee, callback) { * } * callback(); * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * //Error handing + * (async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * })(); + * */ function eachOf(coll, iteratee, callback) { var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; diff --git a/lib/every.js b/lib/every.js index a5ce971cc..9387cb6ba 100644 --- a/lib/every.js +++ b/lib/every.js @@ -23,13 +23,78 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback provided * @example * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * (async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function every(coll, iteratee, callback) { return createTester(bool => !bool, res => !res)(eachOf, coll, iteratee, callback) diff --git a/lib/filter.js b/lib/filter.js index b0f30292d..b4d8af5c1 100644 --- a/lib/filter.js +++ b/lib/filter.js @@ -22,13 +22,53 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback provided * @example * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function filter (coll, iteratee, callback) { return _filter(eachOf, coll, iteratee, callback) diff --git a/lib/groupBy.js b/lib/groupBy.js index 299336722..949372894 100644 --- a/lib/groupBy.js +++ b/lib/groupBy.js @@ -27,15 +27,69 @@ import groupByLimit from './groupByLimit'; * @returns {Promise} a promise, if no callback is passed * @example * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ export default function groupBy (coll, iteratee, callback) { return groupByLimit(coll, Infinity, iteratee, callback) diff --git a/lib/map.js b/lib/map.js index c32bd2dbc..613b07970 100644 --- a/lib/map.js +++ b/lib/map.js @@ -35,9 +35,89 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback is passed * @example * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function map (coll, iteratee, callback) { return _map(eachOf, coll, iteratee, callback) diff --git a/lib/mapValues.js b/lib/mapValues.js index 79edfd46e..ba0682643 100644 --- a/lib/mapValues.js +++ b/lib/mapValues.js @@ -30,20 +30,110 @@ import mapValuesLimit from './mapValuesLimit'; * @returns {Promise} a promise, if no callback is passed * @example * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ export default function mapValues(obj, iteratee, callback) { return mapValuesLimit(obj, Infinity, iteratee, callback) diff --git a/lib/reduce.js b/lib/reduce.js index 571bc5a6f..fcc0075cc 100644 --- a/lib/reduce.js +++ b/lib/reduce.js @@ -35,14 +35,90 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback is passed * @example * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error Handling + * (async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function reduce(coll, memo, iteratee, callback) { callback = once(callback); diff --git a/lib/reject.js b/lib/reject.js index c1de82589..66c5b12cd 100644 --- a/lib/reject.js +++ b/lib/reject.js @@ -21,14 +21,48 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback is passed * @example * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function reject (coll, iteratee, callback) { return _reject(eachOf, coll, iteratee, callback) diff --git a/lib/some.js b/lib/some.js index 378ccdf5d..ad2b3927c 100644 --- a/lib/some.js +++ b/lib/some.js @@ -25,13 +25,79 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback provided * @example * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * (async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ function some(coll, iteratee, callback) { return createTester(Boolean, res => res)(eachOf, coll, iteratee, callback) diff --git a/lib/sortBy.js b/lib/sortBy.js index 4477677e7..3055fc625 100644 --- a/lib/sortBy.js +++ b/lib/sortBy.js @@ -24,31 +24,133 @@ import awaitify from './internal/awaitify' * @returns {Promise} a promise, if no callback passed * @example * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); * * // By modifying the callback parameter the * // sorting order can be influenced: * * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); * * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * (async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * })(); + * */ function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); diff --git a/lib/transform.js b/lib/transform.js index 786f5d391..5ed200e1e 100644 --- a/lib/transform.js +++ b/lib/transform.js @@ -25,26 +25,118 @@ import { promiseCallback, PROMISE_SYMBOL } from './internal/promiseCallback'; * @returns {Promise} a promise, if no callback provided * @example * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc[index] = item * 2 - * callback(null) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } * }); * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * * @example * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * })(); + * */ export default function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3 && typeof accumulator === 'function') { diff --git a/package-lock.json b/package-lock.json index f722fdbc3..bac0918a1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "async", - "version": "3.1.0", + "version": "3.2.0", "lockfileVersion": 1, "requires": true, "dependencies": { From fbf32be159ad4005f4b68b5df8aa5b5aad67350e Mon Sep 17 00:00:00 2001 From: Roman Balayan Date: Tue, 13 Oct 2020 10:08:54 +0800 Subject: [PATCH 2/3] Update collection example code, avoiding usage of IIFE on async/await examples --- docs/v3/concat.js.html | 8 +-- docs/v3/detect.js.html | 4 +- docs/v3/docs.html | 88 ++++++++++++++++----------------- docs/v3/each.js.html | 8 +-- docs/v3/eachOf.js.html | 8 +-- docs/v3/every.js.html | 8 +-- docs/v3/filter.js.html | 4 +- docs/v3/groupBy.js.html | 4 +- docs/v3/map.js.html | 8 +-- docs/v3/mapValues.js.html | 8 +-- docs/v3/module-Collections.html | 88 ++++++++++++++++----------------- docs/v3/reduce.js.html | 8 +-- docs/v3/reject.js.html | 4 +- docs/v3/some.js.html | 8 +-- docs/v3/sortBy.js.html | 4 +- docs/v3/transform.js.html | 4 +- lib/concat.js | 8 +-- lib/detect.js | 4 +- lib/each.js | 8 +-- lib/eachOf.js | 8 +-- lib/every.js | 8 +-- lib/filter.js | 4 +- lib/groupBy.js | 4 +- lib/map.js | 8 +-- lib/mapValues.js | 8 +-- lib/reduce.js | 8 +-- lib/reject.js | 4 +- lib/some.js | 8 +-- lib/sortBy.js | 4 +- lib/transform.js | 4 +- 30 files changed, 176 insertions(+), 176 deletions(-) diff --git a/docs/v3/concat.js.html b/docs/v3/concat.js.html index 9bc898478..3f040619b 100644 --- a/docs/v3/concat.js.html +++ b/docs/v3/concat.js.html @@ -149,7 +149,7 @@

concat.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.concat(directoryList, fs.readdir); * console.log(results); @@ -157,10 +157,10 @@

concat.js

* } catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let results = await async.concat(withMissingDirectoryList, fs.readdir); * console.log(results); @@ -169,7 +169,7 @@

concat.js

* // [ Error: ENOENT: no such file or directory ] * // since dir4 does not exist * } - * })(); + * } * */ function concat(coll, iteratee, callback) { diff --git a/docs/v3/detect.js.html b/docs/v3/detect.js.html index f67e375a1..056000ee7 100644 --- a/docs/v3/detect.js.html +++ b/docs/v3/detect.js.html @@ -137,7 +137,7 @@

detect.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); * console.log(result); @@ -147,7 +147,7 @@

detect.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ function detect(coll, iteratee, callback) { diff --git a/docs/v3/docs.html b/docs/v3/docs.html index 252bcdf46..e8d663e4b 100644 --- a/docs/v3/docs.html +++ b/docs/v3/docs.html @@ -533,7 +533,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.concat(directoryList, fs.readdir); console.log(results); @@ -541,10 +541,10 @@
Example
} catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let results = await async.concat(withMissingDirectoryList, fs.readdir); console.log(results); @@ -553,7 +553,7 @@
Example
// [ Error: ENOENT: no such file or directory ] // since dir4 does not exist } -})();
+}
@@ -1264,7 +1264,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); console.log(result); @@ -1274,7 +1274,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -2019,17 +2019,17 @@
Example
}); // Using async/await -(async () => { +async () => { try { await async.each(files, deleteFile); } catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { await async.each(withMissingFileList, deleteFile); } @@ -2039,7 +2039,7 @@
Example
// since dir4/file2.txt does not exist // dir1/file1.txt could have been deleted } -})(); +} @@ -2583,7 +2583,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.forEachOf(validConfigFileMap, parseFile); console.log(configs); @@ -2593,10 +2593,10 @@
Example
catch (err) { console.log(err); } -})(); +} //Error handing -(async () => { +async () => { try { let result = await async.forEachOf(invalidConfigFileMap, parseFile); console.log(configs); @@ -2605,7 +2605,7 @@
Example
console.log(err); // JSON parse error exception } -})(); +} @@ -3602,7 +3602,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.every(fileList, fileExists); console.log(result); @@ -3612,9 +3612,9 @@
Example
catch (err) { console.log(err); } -})(); +} -(async () => { +async () => { try { let result = await async.every(withMissingFileList, fileExists); console.log(result); @@ -3624,7 +3624,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -4370,7 +4370,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.filter(files, fileExists); console.log(results); @@ -4380,7 +4380,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -5137,7 +5137,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.groupBy(files, detectFile); console.log(result); @@ -5151,7 +5151,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -5918,7 +5918,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.map(fileList, getFileSizeInBytes); console.log(results); @@ -5928,10 +5928,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let results = await async.map(withMissingFileList, getFileSizeInBytes); console.log(results); @@ -5940,7 +5940,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -6712,7 +6712,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.mapValues(fileMap, getFileSizeInBytes); console.log(result); @@ -6726,10 +6726,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); console.log(result); @@ -6738,7 +6738,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -7516,7 +7516,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.reduce(fileList, 0, getFileSizeInBytes); console.log(result); @@ -7526,10 +7526,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); console.log(result); @@ -7538,7 +7538,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -8036,7 +8036,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.reject(fileList, fileExists); console.log(results); @@ -8046,7 +8046,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -8805,7 +8805,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); console.log(result); @@ -8815,9 +8815,9 @@
Example
catch (err) { console.log(err); } -})(); +} -(async () => { +async () => { try { let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); console.log(result); @@ -8827,7 +8827,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -9652,7 +9652,7 @@
Example
})(); // Error handling -(async () => { +async () => { try { let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); console.log(results); @@ -9661,7 +9661,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -10010,7 +10010,7 @@
Examples
}); // Using async/await -(async () => { +async () => { try { let result = await async.transform(fileMap, transformFileSize); console.log(result); @@ -10019,7 +10019,7 @@
Examples
catch (err) { console.log(err); } -})(); +} diff --git a/docs/v3/each.js.html b/docs/v3/each.js.html index 02b4a4688..a4b7c5b4b 100644 --- a/docs/v3/each.js.html +++ b/docs/v3/each.js.html @@ -156,17 +156,17 @@

each.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * await async.each(files, deleteFile); * } * catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * await async.each(withMissingFileList, deleteFile); * } @@ -176,7 +176,7 @@

each.js

* // since dir4/file2.txt does not exist * // dir1/file1.txt could have been deleted * } - * })(); + * } * */ function eachLimit(coll, iteratee, callback) { diff --git a/docs/v3/eachOf.js.html b/docs/v3/eachOf.js.html index a130440d0..132d37bfb 100644 --- a/docs/v3/eachOf.js.html +++ b/docs/v3/eachOf.js.html @@ -200,7 +200,7 @@

eachOf.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.forEachOf(validConfigFileMap, parseFile); * console.log(configs); @@ -210,10 +210,10 @@

eachOf.js

* catch (err) { * console.log(err); * } - * })(); + * } * * //Error handing - * (async () => { + * async () => { * try { * let result = await async.forEachOf(invalidConfigFileMap, parseFile); * console.log(configs); @@ -222,7 +222,7 @@

eachOf.js

* console.log(err); * // JSON parse error exception * } - * })(); + * } * */ function eachOf(coll, iteratee, callback) { diff --git a/docs/v3/every.js.html b/docs/v3/every.js.html index f2f885e5a..7a01ede1f 100644 --- a/docs/v3/every.js.html +++ b/docs/v3/every.js.html @@ -148,7 +148,7 @@

every.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.every(fileList, fileExists); * console.log(result); @@ -158,9 +158,9 @@

every.js

* catch (err) { * console.log(err); * } - * })(); + * } * - * (async () => { + * async () => { * try { * let result = await async.every(withMissingFileList, fileExists); * console.log(result); @@ -170,7 +170,7 @@

every.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ function every(coll, iteratee, callback) { diff --git a/docs/v3/filter.js.html b/docs/v3/filter.js.html index 0ebaa1afd..9d191c72d 100644 --- a/docs/v3/filter.js.html +++ b/docs/v3/filter.js.html @@ -134,7 +134,7 @@

filter.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.filter(files, fileExists); * console.log(results); @@ -144,7 +144,7 @@

filter.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ function filter (coll, iteratee, callback) { diff --git a/docs/v3/groupBy.js.html b/docs/v3/groupBy.js.html index a2b895614..90f578836 100644 --- a/docs/v3/groupBy.js.html +++ b/docs/v3/groupBy.js.html @@ -151,7 +151,7 @@

groupBy.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.groupBy(files, detectFile); * console.log(result); @@ -165,7 +165,7 @@

groupBy.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ export default function groupBy (coll, iteratee, callback) { diff --git a/docs/v3/map.js.html b/docs/v3/map.js.html index 3b4cd0a17..b527c06fb 100644 --- a/docs/v3/map.js.html +++ b/docs/v3/map.js.html @@ -171,7 +171,7 @@

map.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.map(fileList, getFileSizeInBytes); * console.log(results); @@ -181,10 +181,10 @@

map.js

* catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let results = await async.map(withMissingFileList, getFileSizeInBytes); * console.log(results); @@ -193,7 +193,7 @@

map.js

* console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function map (coll, iteratee, callback) { diff --git a/docs/v3/mapValues.js.html b/docs/v3/mapValues.js.html index 58988be55..d1c6dd0a5 100644 --- a/docs/v3/mapValues.js.html +++ b/docs/v3/mapValues.js.html @@ -183,7 +183,7 @@

mapValues.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.mapValues(fileMap, getFileSizeInBytes); * console.log(result); @@ -197,10 +197,10 @@

mapValues.js

* catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); * console.log(result); @@ -209,7 +209,7 @@

mapValues.js

* console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ export default function mapValues(obj, iteratee, callback) { diff --git a/docs/v3/module-Collections.html b/docs/v3/module-Collections.html index b74f70914..6d21404ce 100644 --- a/docs/v3/module-Collections.html +++ b/docs/v3/module-Collections.html @@ -393,7 +393,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.concat(directoryList, fs.readdir); console.log(results); @@ -401,10 +401,10 @@
Example
} catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let results = await async.concat(withMissingDirectoryList, fs.readdir); console.log(results); @@ -413,7 +413,7 @@
Example
// [ Error: ENOENT: no such file or directory ] // since dir4 does not exist } -})(); +} @@ -1124,7 +1124,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); console.log(result); @@ -1134,7 +1134,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -1879,17 +1879,17 @@
Example
}); // Using async/await -(async () => { +async () => { try { await async.each(files, deleteFile); } catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { await async.each(withMissingFileList, deleteFile); } @@ -1899,7 +1899,7 @@
Example
// since dir4/file2.txt does not exist // dir1/file1.txt could have been deleted } -})(); +} @@ -2443,7 +2443,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.forEachOf(validConfigFileMap, parseFile); console.log(configs); @@ -2453,10 +2453,10 @@
Example
catch (err) { console.log(err); } -})(); +} //Error handing -(async () => { +async () => { try { let result = await async.forEachOf(invalidConfigFileMap, parseFile); console.log(configs); @@ -2465,7 +2465,7 @@
Example
console.log(err); // JSON parse error exception } -})(); +} @@ -3462,7 +3462,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.every(fileList, fileExists); console.log(result); @@ -3472,9 +3472,9 @@
Example
catch (err) { console.log(err); } -})(); +} -(async () => { +async () => { try { let result = await async.every(withMissingFileList, fileExists); console.log(result); @@ -3484,7 +3484,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -4230,7 +4230,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.filter(files, fileExists); console.log(results); @@ -4240,7 +4240,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -4997,7 +4997,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.groupBy(files, detectFile); console.log(result); @@ -5011,7 +5011,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -5778,7 +5778,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.map(fileList, getFileSizeInBytes); console.log(results); @@ -5788,10 +5788,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let results = await async.map(withMissingFileList, getFileSizeInBytes); console.log(results); @@ -5800,7 +5800,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -6572,7 +6572,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.mapValues(fileMap, getFileSizeInBytes); console.log(result); @@ -6586,10 +6586,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); console.log(result); @@ -6598,7 +6598,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -7376,7 +7376,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.reduce(fileList, 0, getFileSizeInBytes); console.log(result); @@ -7386,10 +7386,10 @@
Example
catch (err) { console.log(err); } -})(); +} // Error Handling -(async () => { +async () => { try { let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); console.log(result); @@ -7398,7 +7398,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -7896,7 +7896,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let results = await async.reject(fileList, fileExists); console.log(results); @@ -7906,7 +7906,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -8665,7 +8665,7 @@
Example
}); // Using async/await -(async () => { +async () => { try { let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); console.log(result); @@ -8675,9 +8675,9 @@
Example
catch (err) { console.log(err); } -})(); +} -(async () => { +async () => { try { let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); console.log(result); @@ -8687,7 +8687,7 @@
Example
catch (err) { console.log(err); } -})(); +} @@ -9512,7 +9512,7 @@
Example
})(); // Error handling -(async () => { +async () => { try { let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); console.log(results); @@ -9521,7 +9521,7 @@
Example
console.log(err); // [ Error: ENOENT: no such file or directory ] } -})(); +} @@ -9870,7 +9870,7 @@
Examples
}); // Using async/await -(async () => { +async () => { try { let result = await async.transform(fileMap, transformFileSize); console.log(result); @@ -9879,7 +9879,7 @@
Examples
catch (err) { console.log(err); } -})(); +} diff --git a/docs/v3/reduce.js.html b/docs/v3/reduce.js.html index 260b64f5d..c0c3d9eaa 100644 --- a/docs/v3/reduce.js.html +++ b/docs/v3/reduce.js.html @@ -172,7 +172,7 @@

reduce.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.reduce(fileList, 0, getFileSizeInBytes); * console.log(result); @@ -182,10 +182,10 @@

reduce.js

* catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); * console.log(result); @@ -194,7 +194,7 @@

reduce.js

* console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function reduce(coll, memo, iteratee, callback) { diff --git a/docs/v3/reject.js.html b/docs/v3/reject.js.html index eeb3b50d6..18048d955 100644 --- a/docs/v3/reject.js.html +++ b/docs/v3/reject.js.html @@ -128,7 +128,7 @@

reject.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.reject(fileList, fileExists); * console.log(results); @@ -138,7 +138,7 @@

reject.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ function reject (coll, iteratee, callback) { diff --git a/docs/v3/some.js.html b/docs/v3/some.js.html index e6b03c5a1..4d89facb6 100644 --- a/docs/v3/some.js.html +++ b/docs/v3/some.js.html @@ -151,7 +151,7 @@

some.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); * console.log(result); @@ -161,9 +161,9 @@

some.js

* catch (err) { * console.log(err); * } - * })(); + * } * - * (async () => { + * async () => { * try { * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); * console.log(result); @@ -173,7 +173,7 @@

some.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ function some(coll, iteratee, callback) { diff --git a/docs/v3/sortBy.js.html b/docs/v3/sortBy.js.html index 840916724..7bd91eda8 100644 --- a/docs/v3/sortBy.js.html +++ b/docs/v3/sortBy.js.html @@ -217,7 +217,7 @@

sortBy.js

* })(); * * // Error handling - * (async () => { + * async () => { * try { * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); * console.log(results); @@ -226,7 +226,7 @@

sortBy.js

* console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function sortBy (coll, iteratee, callback) { diff --git a/docs/v3/transform.js.html b/docs/v3/transform.js.html index ab73bc033..cb5324abf 100644 --- a/docs/v3/transform.js.html +++ b/docs/v3/transform.js.html @@ -203,7 +203,7 @@

transform.js

* }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.transform(fileMap, transformFileSize); * console.log(result); @@ -212,7 +212,7 @@

transform.js

* catch (err) { * console.log(err); * } - * })(); + * } * */ export default function transform (coll, accumulator, iteratee, callback) { diff --git a/lib/concat.js b/lib/concat.js index 37561c143..73435ded9 100644 --- a/lib/concat.js +++ b/lib/concat.js @@ -72,7 +72,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.concat(directoryList, fs.readdir); * console.log(results); @@ -80,10 +80,10 @@ import awaitify from './internal/awaitify' * } catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let results = await async.concat(withMissingDirectoryList, fs.readdir); * console.log(results); @@ -92,7 +92,7 @@ import awaitify from './internal/awaitify' * // [ Error: ENOENT: no such file or directory ] * // since dir4 does not exist * } - * })(); + * } * */ function concat(coll, iteratee, callback) { diff --git a/lib/detect.js b/lib/detect.js index d70e8c00c..0b63df46a 100644 --- a/lib/detect.js +++ b/lib/detect.js @@ -60,7 +60,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); * console.log(result); @@ -70,7 +70,7 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * */ function detect(coll, iteratee, callback) { diff --git a/lib/each.js b/lib/each.js index ea0798b16..e4cde8c10 100644 --- a/lib/each.js +++ b/lib/each.js @@ -79,17 +79,17 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * await async.each(files, deleteFile); * } * catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * await async.each(withMissingFileList, deleteFile); * } @@ -99,7 +99,7 @@ import awaitify from './internal/awaitify' * // since dir4/file2.txt does not exist * // dir1/file1.txt could have been deleted * } - * })(); + * } * */ function eachLimit(coll, iteratee, callback) { diff --git a/lib/eachOf.js b/lib/eachOf.js index 5c655b212..207cec0ff 100644 --- a/lib/eachOf.js +++ b/lib/eachOf.js @@ -123,7 +123,7 @@ function eachOfGeneric (coll, iteratee, callback) { * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.forEachOf(validConfigFileMap, parseFile); * console.log(configs); @@ -133,10 +133,10 @@ function eachOfGeneric (coll, iteratee, callback) { * catch (err) { * console.log(err); * } - * })(); + * } * * //Error handing - * (async () => { + * async () => { * try { * let result = await async.forEachOf(invalidConfigFileMap, parseFile); * console.log(configs); @@ -145,7 +145,7 @@ function eachOfGeneric (coll, iteratee, callback) { * console.log(err); * // JSON parse error exception * } - * })(); + * } * */ function eachOf(coll, iteratee, callback) { diff --git a/lib/every.js b/lib/every.js index 9387cb6ba..0a6bc5496 100644 --- a/lib/every.js +++ b/lib/every.js @@ -71,7 +71,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.every(fileList, fileExists); * console.log(result); @@ -81,9 +81,9 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * - * (async () => { + * async () => { * try { * let result = await async.every(withMissingFileList, fileExists); * console.log(result); @@ -93,7 +93,7 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * */ function every(coll, iteratee, callback) { diff --git a/lib/filter.js b/lib/filter.js index b4d8af5c1..24285500a 100644 --- a/lib/filter.js +++ b/lib/filter.js @@ -57,7 +57,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.filter(files, fileExists); * console.log(results); @@ -67,7 +67,7 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * */ function filter (coll, iteratee, callback) { diff --git a/lib/groupBy.js b/lib/groupBy.js index 949372894..c6949b25f 100644 --- a/lib/groupBy.js +++ b/lib/groupBy.js @@ -74,7 +74,7 @@ import groupByLimit from './groupByLimit'; * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.groupBy(files, detectFile); * console.log(result); @@ -88,7 +88,7 @@ import groupByLimit from './groupByLimit'; * catch (err) { * console.log(err); * } - * })(); + * } * */ export default function groupBy (coll, iteratee, callback) { diff --git a/lib/map.js b/lib/map.js index 613b07970..13646c974 100644 --- a/lib/map.js +++ b/lib/map.js @@ -94,7 +94,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.map(fileList, getFileSizeInBytes); * console.log(results); @@ -104,10 +104,10 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let results = await async.map(withMissingFileList, getFileSizeInBytes); * console.log(results); @@ -116,7 +116,7 @@ import awaitify from './internal/awaitify' * console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function map (coll, iteratee, callback) { diff --git a/lib/mapValues.js b/lib/mapValues.js index ba0682643..0d44ce464 100644 --- a/lib/mapValues.js +++ b/lib/mapValues.js @@ -106,7 +106,7 @@ import mapValuesLimit from './mapValuesLimit'; * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.mapValues(fileMap, getFileSizeInBytes); * console.log(result); @@ -120,10 +120,10 @@ import mapValuesLimit from './mapValuesLimit'; * catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); * console.log(result); @@ -132,7 +132,7 @@ import mapValuesLimit from './mapValuesLimit'; * console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ export default function mapValues(obj, iteratee, callback) { diff --git a/lib/reduce.js b/lib/reduce.js index fcc0075cc..a024d13bd 100644 --- a/lib/reduce.js +++ b/lib/reduce.js @@ -95,7 +95,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.reduce(fileList, 0, getFileSizeInBytes); * console.log(result); @@ -105,10 +105,10 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * * // Error Handling - * (async () => { + * async () => { * try { * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); * console.log(result); @@ -117,7 +117,7 @@ import awaitify from './internal/awaitify' * console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function reduce(coll, memo, iteratee, callback) { diff --git a/lib/reject.js b/lib/reject.js index 66c5b12cd..127430e10 100644 --- a/lib/reject.js +++ b/lib/reject.js @@ -51,7 +51,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let results = await async.reject(fileList, fileExists); * console.log(results); @@ -61,7 +61,7 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * */ function reject (coll, iteratee, callback) { diff --git a/lib/some.js b/lib/some.js index ad2b3927c..1d7f6fd1e 100644 --- a/lib/some.js +++ b/lib/some.js @@ -74,7 +74,7 @@ import awaitify from './internal/awaitify' * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); * console.log(result); @@ -84,9 +84,9 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * - * (async () => { + * async () => { * try { * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); * console.log(result); @@ -96,7 +96,7 @@ import awaitify from './internal/awaitify' * catch (err) { * console.log(err); * } - * })(); + * } * */ function some(coll, iteratee, callback) { diff --git a/lib/sortBy.js b/lib/sortBy.js index 3055fc625..7a1b9fbbb 100644 --- a/lib/sortBy.js +++ b/lib/sortBy.js @@ -140,7 +140,7 @@ import awaitify from './internal/awaitify' * })(); * * // Error handling - * (async () => { + * async () => { * try { * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); * console.log(results); @@ -149,7 +149,7 @@ import awaitify from './internal/awaitify' * console.log(err); * // [ Error: ENOENT: no such file or directory ] * } - * })(); + * } * */ function sortBy (coll, iteratee, callback) { diff --git a/lib/transform.js b/lib/transform.js index 5ed200e1e..d2aa29e7f 100644 --- a/lib/transform.js +++ b/lib/transform.js @@ -126,7 +126,7 @@ import { promiseCallback, PROMISE_SYMBOL } from './internal/promiseCallback'; * }); * * // Using async/await - * (async () => { + * async () => { * try { * let result = await async.transform(fileMap, transformFileSize); * console.log(result); @@ -135,7 +135,7 @@ import { promiseCallback, PROMISE_SYMBOL } from './internal/promiseCallback'; * catch (err) { * console.log(err); * } - * })(); + * } * */ export default function transform (coll, accumulator, iteratee, callback) { From 4be49ac1400f28eed1c040709bce35e862e7cc84 Mon Sep 17 00:00:00 2001 From: Roman Balayan Date: Thu, 15 Oct 2020 22:40:25 +0800 Subject: [PATCH 3/3] Convert examples on async.auto, async.series, and async.parallel to samples using Promises and async/await --- docs/v3/auto.js.html | 88 +++++++-- docs/v3/docs.html | 314 ++++++++++++++++++++++++++++---- docs/v3/module-ControlFlow.html | 314 ++++++++++++++++++++++++++++---- docs/v3/parallel.js.html | 99 +++++++++- docs/v3/series.js.html | 120 +++++++++++- lib/auto.js | 88 +++++++-- lib/parallel.js | 99 +++++++++- lib/series.js | 120 +++++++++++- 8 files changed, 1126 insertions(+), 116 deletions(-) diff --git a/docs/v3/auto.js.html b/docs/v3/auto.js.html index e380d6568..a1d65dbc5 100644 --- a/docs/v3/auto.js.html +++ b/docs/v3/auto.js.html @@ -121,15 +121,40 @@

auto.js

* @returns {Promise} a promise, if a callback is not passed * @example * + * //Using Callbacks * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); * }] - * }, callback); + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); * + * //Using Promises * async.auto({ * get_data: function(callback) { * console.log('in get_data'); @@ -143,21 +168,62 @@

auto.js

* callback(null, 'folder'); * }, * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); * // once there is some data and the directory exists, * // write the data to a file in the directory * callback(null, 'filename'); * }], * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. * callback(null, {'file':results.write_file, 'email':'user@example.com'}); * }] - * }, function(err, results) { - * console.log('err = ', err); + * }).then(results => { * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function auto(tasks, concurrency, callback) { if (typeof concurrency !== 'number') { diff --git a/docs/v3/docs.html b/docs/v3/docs.html index e8d663e4b..e4ff9a39a 100644 --- a/docs/v3/docs.html +++ b/docs/v3/docs.html @@ -10880,15 +10880,40 @@
Returns:
Example
-
async.auto({
-    // this function will just be passed a callback
-    readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
-    showData: ['readData', function(results, cb) {
-        // results.readData is the file's contents
-        // ...
+    
//Using Callbacks
+async.auto({
+    get_data: function(callback) {
+        // async code to get some data
+        callback(null, 'data', 'converted to array');
+    },
+    make_folder: function(callback) {
+        // async code to create a directory to store a file in
+        // this is run at the same time as getting the data
+        callback(null, 'folder');
+    },
+    write_file: ['get_data', 'make_folder', function(results, callback) {
+        // once there is some data and the directory exists,
+        // write the data to a file in the directory
+        callback(null, 'filename');
+    }],
+    email_link: ['write_file', function(results, callback) {
+        // once the file is written let's email a link to it...
+        callback(null, {'file':results.write_file, 'email':'user@example.com'});
     }]
-}, callback);
+}, function(err, results) {
+    if (err) {
+        console.log('err = ', err);
+    }
+    console.log('results = ', results);
+    // results = {
+    //     get_data: ['data', 'converted to array']
+    //     make_folder; 'folder',
+    //     write_file: 'filename'
+    //     email_link: { file: 'filename', email: 'user@example.com' }
+    // }
+});
 
+//Using Promises
 async.auto({
     get_data: function(callback) {
         console.log('in get_data');
@@ -10902,21 +10927,61 @@ 
Example
callback(null, 'folder'); }, write_file: ['get_data', 'make_folder', function(results, callback) { - console.log('in write_file', JSON.stringify(results)); // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }], email_link: ['write_file', function(results, callback) { - console.log('in email_link', JSON.stringify(results)); // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. callback(null, {'file':results.write_file, 'email':'user@example.com'}); }] -}, function(err, results) { - console.log('err = ', err); +}).then(results => { console.log('results = ', results); -});
+ // results = { + // get_data: ['data', 'converted to array'] + // make_folder; 'folder', + // write_file: 'filename' + // email_link: { file: 'filename', email: 'user@example.com' } + // } +}).catch(err => { + console.log('err = ', err); +}); + +//Using async/await +async () => { + try { + let results = await async.auto({ + get_data: function(callback) { + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback) { + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(results, callback) { + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(results, callback) { + // once the file is written let's email a link to it... + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] + }); + console.log('results = ', results); + // results = { + // get_data: ['data', 'converted to array'] + // make_folder; 'folder', + // write_file: 'filename' + // email_link: { file: 'filename', email: 'user@example.com' } + // } + } + catch (err) { + console.log(err); + } +}
@@ -12719,7 +12784,8 @@
Returns:
Example
-
async.parallel([
+    
//Using Callbacks
+async.parallel([
     function(callback) {
         setTimeout(function() {
             callback(null, 'one');
@@ -12730,10 +12796,9 @@ 
Example
callback(null, 'two'); }, 100); } -], -// optional callback -function(err, results) { - // the results array will equal ['one','two'] even though +], function(err, results) { + console.log(results); + // results is equal to ['one','two'] even though // the second function had a shorter timeout. }); @@ -12750,8 +12815,95 @@
Example
}, 100); } }, function(err, results) { - // results is now equals to: {one: 1, two: 2} -});
+ console.log(results); + // results is equal to: { one: 1, two: 2 } +}); + +//Using Promises +async.parallel([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } +]).then(results => { + console.log(results); + // results is equal to ['one','two'] even though + // the second function had a shorter timeout. +}).catch(err => { + console.log(err); +}); + +// an example using an object instead of an array +async.parallel({ + one: function(callback) { + setTimeout(function() { + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + callback(null, 2); + }, 100); + } +}).then(results => { + console.log(results); + // results is equal to: { one: 1, two: 2 } +}).catch(err => { + console.log(err); +}); + +//Using async/await +async () => { + try { + let results = await async.parallel([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } + ]); + console.log(results); + // results is equal to ['one','two'] even though + // the second function had a shorter timeout. + } + catch (err) { + console.log(err); + } +} + +// an example using an object instead of an array +async () => { + try { + let results = await async.parallel({ + one: function(callback) { + setTimeout(function() { + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + callback(null, 2); + }, 100); + } + }); + console.log(results); + // results is equal to: { one: 1, two: 2 } + } + catch (err) { + console.log(err); + } +}
@@ -14540,35 +14692,133 @@
Returns:
Example
-
async.series([
+    
//Using Callbacks
+async.series([
     function(callback) {
-        // do some stuff ...
-        callback(null, 'one');
+        setTimeout(function() {
+            // do some async task
+            callback(null, 'one');
+        }, 200);
     },
     function(callback) {
-        // do some more stuff ...
-        callback(null, 'two');
+        setTimeout(function() {
+            // then do another async task
+            callback(null, 'two');
+        }, 100);
     }
-],
-// optional callback
-function(err, results) {
-    // results is now equal to ['one', 'two']
+], function(err, results) {
+    console.log(results);
+    // results is equal to ['one','two']
 });
 
+// an example using objects instead of arrays
 async.series({
     one: function(callback) {
         setTimeout(function() {
+            // do some async task
             callback(null, 1);
         }, 200);
     },
-    two: function(callback){
+    two: function(callback) {
         setTimeout(function() {
+            // then do another async task
             callback(null, 2);
         }, 100);
     }
 }, function(err, results) {
-    // results is now equal to: {one: 1, two: 2}
-});
+ console.log(results); + // results is equal to: { one: 1, two: 2 } +}); + +//Using Promises +async.series([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } +]).then(results => { + console.log(results); + // results is equal to ['one','two'] +}).catch(err => { + console.log(err); +}); + +// an example using an object instead of an array +async.series({ + one: function(callback) { + setTimeout(function() { + // do some async task + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 2); + }, 100); + } +}).then(results => { + console.log(results); + // results is equal to: { one: 1, two: 2 } +}).catch(err => { + console.log(err); +}); + +//Using async/await +async () => { + try { + let results = await async.series([ + function(callback) { + setTimeout(function() { + // do some async task + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 'two'); + }, 100); + } + ]); + console.log(results); + // results is equal to ['one','two'] + } + catch (err) { + console.log(err); + } +} + +// an example using an object instead of an array +async () => { + try { + let results = await async.parallel({ + one: function(callback) { + setTimeout(function() { + // do some async task + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 2); + }, 100); + } + }); + console.log(results); + // results is equal to: { one: 1, two: 2 } + } + catch (err) { + console.log(err); + } +}
diff --git a/docs/v3/module-ControlFlow.html b/docs/v3/module-ControlFlow.html index 472aeb83b..d48a8a7a9 100644 --- a/docs/v3/module-ControlFlow.html +++ b/docs/v3/module-ControlFlow.html @@ -853,15 +853,40 @@
Returns:
Example
-
async.auto({
-    // this function will just be passed a callback
-    readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
-    showData: ['readData', function(results, cb) {
-        // results.readData is the file's contents
-        // ...
+    
//Using Callbacks
+async.auto({
+    get_data: function(callback) {
+        // async code to get some data
+        callback(null, 'data', 'converted to array');
+    },
+    make_folder: function(callback) {
+        // async code to create a directory to store a file in
+        // this is run at the same time as getting the data
+        callback(null, 'folder');
+    },
+    write_file: ['get_data', 'make_folder', function(results, callback) {
+        // once there is some data and the directory exists,
+        // write the data to a file in the directory
+        callback(null, 'filename');
+    }],
+    email_link: ['write_file', function(results, callback) {
+        // once the file is written let's email a link to it...
+        callback(null, {'file':results.write_file, 'email':'user@example.com'});
     }]
-}, callback);
+}, function(err, results) {
+    if (err) {
+        console.log('err = ', err);
+    }
+    console.log('results = ', results);
+    // results = {
+    //     get_data: ['data', 'converted to array']
+    //     make_folder; 'folder',
+    //     write_file: 'filename'
+    //     email_link: { file: 'filename', email: 'user@example.com' }
+    // }
+});
 
+//Using Promises
 async.auto({
     get_data: function(callback) {
         console.log('in get_data');
@@ -875,21 +900,61 @@ 
Example
callback(null, 'folder'); }, write_file: ['get_data', 'make_folder', function(results, callback) { - console.log('in write_file', JSON.stringify(results)); // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }], email_link: ['write_file', function(results, callback) { - console.log('in email_link', JSON.stringify(results)); // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. callback(null, {'file':results.write_file, 'email':'user@example.com'}); }] -}, function(err, results) { - console.log('err = ', err); +}).then(results => { console.log('results = ', results); -});
+ // results = { + // get_data: ['data', 'converted to array'] + // make_folder; 'folder', + // write_file: 'filename' + // email_link: { file: 'filename', email: 'user@example.com' } + // } +}).catch(err => { + console.log('err = ', err); +}); + +//Using async/await +async () => { + try { + let results = await async.auto({ + get_data: function(callback) { + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback) { + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(results, callback) { + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(results, callback) { + // once the file is written let's email a link to it... + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] + }); + console.log('results = ', results); + // results = { + // get_data: ['data', 'converted to array'] + // make_folder; 'folder', + // write_file: 'filename' + // email_link: { file: 'filename', email: 'user@example.com' } + // } + } + catch (err) { + console.log(err); + } +}
@@ -2692,7 +2757,8 @@
Returns:
Example
-
async.parallel([
+    
//Using Callbacks
+async.parallel([
     function(callback) {
         setTimeout(function() {
             callback(null, 'one');
@@ -2703,10 +2769,9 @@ 
Example
callback(null, 'two'); }, 100); } -], -// optional callback -function(err, results) { - // the results array will equal ['one','two'] even though +], function(err, results) { + console.log(results); + // results is equal to ['one','two'] even though // the second function had a shorter timeout. }); @@ -2723,8 +2788,95 @@
Example
}, 100); } }, function(err, results) { - // results is now equals to: {one: 1, two: 2} -});
+ console.log(results); + // results is equal to: { one: 1, two: 2 } +}); + +//Using Promises +async.parallel([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } +]).then(results => { + console.log(results); + // results is equal to ['one','two'] even though + // the second function had a shorter timeout. +}).catch(err => { + console.log(err); +}); + +// an example using an object instead of an array +async.parallel({ + one: function(callback) { + setTimeout(function() { + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + callback(null, 2); + }, 100); + } +}).then(results => { + console.log(results); + // results is equal to: { one: 1, two: 2 } +}).catch(err => { + console.log(err); +}); + +//Using async/await +async () => { + try { + let results = await async.parallel([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } + ]); + console.log(results); + // results is equal to ['one','two'] even though + // the second function had a shorter timeout. + } + catch (err) { + console.log(err); + } +} + +// an example using an object instead of an array +async () => { + try { + let results = await async.parallel({ + one: function(callback) { + setTimeout(function() { + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + callback(null, 2); + }, 100); + } + }); + console.log(results); + // results is equal to: { one: 1, two: 2 } + } + catch (err) { + console.log(err); + } +}
@@ -4513,35 +4665,133 @@
Returns:
Example
-
async.series([
+    
//Using Callbacks
+async.series([
     function(callback) {
-        // do some stuff ...
-        callback(null, 'one');
+        setTimeout(function() {
+            // do some async task
+            callback(null, 'one');
+        }, 200);
     },
     function(callback) {
-        // do some more stuff ...
-        callback(null, 'two');
+        setTimeout(function() {
+            // then do another async task
+            callback(null, 'two');
+        }, 100);
     }
-],
-// optional callback
-function(err, results) {
-    // results is now equal to ['one', 'two']
+], function(err, results) {
+    console.log(results);
+    // results is equal to ['one','two']
 });
 
+// an example using objects instead of arrays
 async.series({
     one: function(callback) {
         setTimeout(function() {
+            // do some async task
             callback(null, 1);
         }, 200);
     },
-    two: function(callback){
+    two: function(callback) {
         setTimeout(function() {
+            // then do another async task
             callback(null, 2);
         }, 100);
     }
 }, function(err, results) {
-    // results is now equal to: {one: 1, two: 2}
-});
+ console.log(results); + // results is equal to: { one: 1, two: 2 } +}); + +//Using Promises +async.series([ + function(callback) { + setTimeout(function() { + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + callback(null, 'two'); + }, 100); + } +]).then(results => { + console.log(results); + // results is equal to ['one','two'] +}).catch(err => { + console.log(err); +}); + +// an example using an object instead of an array +async.series({ + one: function(callback) { + setTimeout(function() { + // do some async task + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 2); + }, 100); + } +}).then(results => { + console.log(results); + // results is equal to: { one: 1, two: 2 } +}).catch(err => { + console.log(err); +}); + +//Using async/await +async () => { + try { + let results = await async.series([ + function(callback) { + setTimeout(function() { + // do some async task + callback(null, 'one'); + }, 200); + }, + function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 'two'); + }, 100); + } + ]); + console.log(results); + // results is equal to ['one','two'] + } + catch (err) { + console.log(err); + } +} + +// an example using an object instead of an array +async () => { + try { + let results = await async.parallel({ + one: function(callback) { + setTimeout(function() { + // do some async task + callback(null, 1); + }, 200); + }, + two: function(callback) { + setTimeout(function() { + // then do another async task + callback(null, 2); + }, 100); + } + }); + console.log(results); + // results is equal to: { one: 1, two: 2 } + } + catch (err) { + console.log(err); + } +}
diff --git a/docs/v3/parallel.js.html b/docs/v3/parallel.js.html index 946909ea6..40af8d334 100644 --- a/docs/v3/parallel.js.html +++ b/docs/v3/parallel.js.html @@ -114,6 +114,8 @@

parallel.js

* @returns {Promise} a promise, if a callback is not passed * * @example + * + * //Using Callbacks * async.parallel([ * function(callback) { * setTimeout(function() { @@ -125,10 +127,9 @@

parallel.js

* callback(null, 'two'); * }, 100); * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though * // the second function had a shorter timeout. * }); * @@ -145,8 +146,96 @@

parallel.js

* }, 100); * } * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} + * console.log(results); + * // results is equal to: { one: 1, two: 2 } * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function parallel(tasks, callback) { return _parallel(eachOf, tasks, callback); diff --git a/docs/v3/series.js.html b/docs/v3/series.js.html index 02b62f317..bef4a61e7 100644 --- a/docs/v3/series.js.html +++ b/docs/v3/series.js.html @@ -113,35 +113,135 @@

series.js

* with (err, result). * @return {Promise} a promise, if no callback is passed * @example + * + * //Using Callbacks * async.series([ * function(callback) { - * // do some stuff ... - * callback(null, 'one'); + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); * }, * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] * }); * + * // an example using objects instead of arrays * async.series({ * one: function(callback) { * setTimeout(function() { + * // do some async task * callback(null, 1); * }, 200); * }, - * two: function(callback){ + * two: function(callback) { * setTimeout(function() { + * // then do another async task * callback(null, 2); * }, 100); * } * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function series(tasks, callback) { return _parallel(eachOfSeries, tasks, callback); diff --git a/lib/auto.js b/lib/auto.js index ad92d74de..58a8c4570 100644 --- a/lib/auto.js +++ b/lib/auto.js @@ -44,15 +44,40 @@ import { promiseCallback, PROMISE_SYMBOL } from './internal/promiseCallback' * @returns {Promise} a promise, if a callback is not passed * @example * + * //Using Callbacks * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); * }] - * }, callback); + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); * + * //Using Promises * async.auto({ * get_data: function(callback) { * console.log('in get_data'); @@ -66,21 +91,62 @@ import { promiseCallback, PROMISE_SYMBOL } from './internal/promiseCallback' * callback(null, 'folder'); * }, * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); * // once there is some data and the directory exists, * // write the data to a file in the directory * callback(null, 'filename'); * }], * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. * callback(null, {'file':results.write_file, 'email':'user@example.com'}); * }] - * }, function(err, results) { - * console.log('err = ', err); + * }).then(results => { * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function auto(tasks, concurrency, callback) { if (typeof concurrency !== 'number') { diff --git a/lib/parallel.js b/lib/parallel.js index fafae9df7..1124ac38f 100644 --- a/lib/parallel.js +++ b/lib/parallel.js @@ -37,6 +37,8 @@ import _parallel from './internal/parallel'; * @returns {Promise} a promise, if a callback is not passed * * @example + * + * //Using Callbacks * async.parallel([ * function(callback) { * setTimeout(function() { @@ -48,10 +50,9 @@ import _parallel from './internal/parallel'; * callback(null, 'two'); * }, 100); * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though * // the second function had a shorter timeout. * }); * @@ -68,8 +69,96 @@ import _parallel from './internal/parallel'; * }, 100); * } * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} + * console.log(results); + * // results is equal to: { one: 1, two: 2 } * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function parallel(tasks, callback) { return _parallel(eachOf, tasks, callback); diff --git a/lib/series.js b/lib/series.js index 71367a954..cbec2e834 100644 --- a/lib/series.js +++ b/lib/series.js @@ -36,35 +36,135 @@ import eachOfSeries from './eachOfSeries'; * with (err, result). * @return {Promise} a promise, if no callback is passed * @example + * + * //Using Callbacks * async.series([ * function(callback) { - * // do some stuff ... - * callback(null, 'one'); + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); * }, * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] * }); * + * // an example using objects instead of arrays * async.series({ * one: function(callback) { * setTimeout(function() { + * // do some async task * callback(null, 1); * }, 200); * }, - * two: function(callback){ + * two: function(callback) { * setTimeout(function() { + * // then do another async task * callback(null, 2); * }, 100); * } * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * */ export default function series(tasks, callback) { return _parallel(eachOfSeries, tasks, callback);