Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 20th, 2012  |  syntax: JavaScript  |  size: 1.08 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //var util = require("util"); // check
  2.  
  3. function prepare_file(path, callback) {
  4.         setTimeout(function () {
  5.                 callback(path + "_found");
  6.                 // what if we change a little our requirements?        
  7.                 /*
  8.                 if(path!='c')
  9.                         callback(path + "_found");
  10.                 else callback();
  11.                 */
  12.         }, 1000*Math.random());
  13. };
  14.  
  15. function process_files(files, callback){
  16.         var cont = {}
  17.                 , remains = files.length;
  18.         function process_file_intern(path){
  19.                 prepare_file(path, function(path_result){
  20.                         if(path_result) cont[path] = path_result;
  21.                         if(--remains===0){// last file? run callback then
  22.                                 var ret = [];
  23.                                 for(var i = 0; i<files.length;++i){
  24.                                         var curr_file_path = cont[files[i]];
  25.                                         if(!curr_file_path) continue;
  26.                                         ret.push(curr_file_path);
  27.                                 }
  28.                                 callback(ret);
  29.                         }
  30.                 });
  31.         };
  32.         for(var i = 0; i<files.length;++i){
  33.                 process_file_intern(files[i]);
  34.         }
  35. }
  36.  
  37. // what if you pass other items like 'd_', 'other_file_if_found'
  38. process_files(['a', 'b', 'c'], function (paths) {
  39.         // console.log("result:"+util.inspect(paths)); //check
  40.         // paths should equal ['a_found', 'b_found', 'c_found']
  41. });