如何在映射和缩减后访问原始单条目

How to access original single entries after map and reduce

本文关键字:访问 原始 单条目 映射      更新时间:2023-09-26

给定以下函数:

var files = [file1,file2,file3]    
files.map(doSomethingWithFile).reduce(function (sequence, filePromise) {
    return sequence.then(function () {
      return filePromise;
    }).then(function (content, err) {
        //doSomethingWith(file,content)   <-- How to access current file (either file1,file2 or file3)
    });

我如何访问'file',这将是文件中的单个元素?因为'then'保证对它进行排序,所以我知道第一次输入最后一个then时,file1是要映射的元素。之后file2, file3…

然而,除了使用递增索引直接处理原始文件和结果之外,还有其他方法吗?

Map和reduce没有就地修改,因此原始文件数组仍然存在。此外,您可以传递第三个参数来reduce,这是当前索引。您可以使用此参数访问原始数组

的相应元素。
var files = [file1,file2,file3]    
files
  .map(doSomethingWithFile)
  .reduce(function(sequence, filePromise, i) {
    return sequence.then(function() {
      return filePromise;
    }).then(function (content, err) {
      doSomethingWith(file[i], content)   // i comes from .reduce()
});

让您的map函数返回一个包装器对象,其中包含对文件和承诺的引用。

即…

function doSomethingWithFile(file){
  //do something
  return {file:file, promise:...}
}
files.map(doSomethingWithFiles).reduce(function(sequence, wrapper){
  wrapper.file;
  wrapper.promise;
});