Promise how to implement in this situation?

半腔热情 提交于 2019-12-04 20:19:26

uhm it seems you are trying to read files in the loop cycle then, but in a async way. First question, is why async reading those files? You can always read them in sync way:

var data=fs.readFileSync(fname, encoding);

By the way, if you wish to read them async and keep the for...loop you need something like a Promise, or a timed wait or a more complex synchronization mechanism.

You can keep it simple, without using any other packages/modules in this way:

/**
       * Promise.All
       * @param items Array of objects
       * @param block Function block(item,index,resolve,reject)
       * @param done Function Success block
       * @param fail Function Failure block
       * @example

          promiseAll(["a","b","c"],
          function(item,index,resolve,reject) {
            MyApp.call(item,function(result) {
              resolve(result);
            },
            function( error ) { reject(error); }):
          },
          function(result) { // aggregated results

          },function(error) { // error

          })

        * @author Loreto Parisi (loretoparisi at gmail dot com)
       */
    promiseAll: function(items, block, done, fail) {
            var self = this;
            var promises = [],
                index = 0;
            items.forEach(function(item) {
                promises.push(function(item, i) {
                    return new Promise(function(resolve, reject) {
                        if (block) {
                            block.apply(this, [item, index, resolve, reject]);
                        }
                    });
                }(item, ++index))
            });
            Promise.all(promises).then(function AcceptHandler(results) {
                if (done) done(results);
            }, function ErrorHandler(error) {
                if (fail) fail(error);
            });
        }, //promiseAll

so you can call it like

promiseAll(arrayOfItems, function(item, index, resolve, reject) {
    // do something on item
    if (someSuccessCondOnThisItem) {
        resolve(item)
    } else {
        reject(new Error("operation failed"))
    }
}, function(results) { // aggregated results

    console.log("All done %d", results.length);

}, function(error) { // error
    console.log(error.toString());
});

Keep in mind that this is a very simplified approach, but in most of cases it works when cycling through arrays.

Here is a simple working example in the playground:

var console = {
 log : function(s) { document.getElementById("console").innerHTML+=s+"<br/>"}
}
var promiseAll= function(items, block, done, fail) {
            var self = this;
            var promises = [],
                index = 0;
            items.forEach(function(item) {
                promises.push(function(item, i) {
                    return new Promise(function(resolve, reject) {
                        if (block) {
                            block.apply(this, [item, index, resolve, reject]);
                        }
                    });
                }(item, ++index))
            });
            Promise.all(promises).then(function AcceptHandler(results) {
                if (done) done(results);
            }, function ErrorHandler(error) {
                if (fail) fail(error);
            });
        }; //promiseAll

arr=[1,2,3]
promiseAll(arr
                ,function(item,index,resolve,reject) {
                  console.log("Resolving item[" + index+"]")
                  var okCond=true
                  if(okCond) {resolve(item)} else { reject(new Error("item[" + index+"]")) }
                }
                ,function(results) { // aggregated results
console.log("All done of "+results.length);
                }
                ,function(error) { // error
                console.log(error);
 });
<div id="console"/>

Finally, a complete asynchronous example, showing how to defer execution of a XMLHttpRequest, when cycling through a list. The ExecutionBlock is calling reject and resolve after the SimpleRequest responds, causing the Promise the wait its execution before calling the then.

var console = {
    log: function(s) {
      document.getElementById("console").innerHTML += s + "<br/>"
    }
  }
  // Simple XMLHttpRequest
  // based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
    call: function(what, response) {
      var request;
      if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        request = new XMLHttpRequest();
      } else if (window.ActiveXObject) { // IE
        try {
          request = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
          try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
          } catch (e) {}
        }
      }
      // state changes
      request.onreadystatechange = function() {
        if (request.readyState === 4) { // done
          if (request.status === 200) { // complete	
            response(request.responseText)
          } else response();
        }
      }
      request.open('GET', what, true);
      request.send(null);
    }
  }
  //PromiseAll
var promiseAll = function(items, block, done, fail) {
  var self = this;
  var promises = [],
    index = 0;
  items.forEach(function(item) {
    promises.push(function(item, i) {
      return new Promise(function(resolve, reject) {
        if (block) {
          block.apply(this, [item, index, resolve, reject]);
        }
      });
    }(item, ++index))
  });
  Promise.all(promises).then(function AcceptHandler(results) {
    if (done) done(results);
  }, function ErrorHandler(error) {
    if (fail) fail(error);
  });
}; //promiseAll

// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
  SimpleRequest.call('https://icanhazip.com/', function(result) {
    if (result) {
      console.log("Response[" + index + "] " + result);
      resolve(result);
    } else {
      reject(new Error("call error"));
    }
  })
}

arr = [1, 2, 3]
promiseAll(arr, function(item, index, resolve, reject) {
  console.log("Making request [" + index + "]")
  ExecutionBlock(item, index, resolve, reject);
}, function(results) { // aggregated results
  console.log("All response received " + results.length);
  console.log(JSON.stringify(results));
}, function(error) { // error
  console.log(error);
});
<div id="console" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!