JavaScript - 在进入循环的下一次迭代之前等待函数完成处理

JavaScript - wait for a function to finish processing before going to the next iteration of the loop

我想让一个函数等待另一个函数完全完成。我们有这个函数来处理文件列表并将每个文件加载到 loadFileIntoMemory 函数中。

我希望此函数等待 loadFileIntoMemory 函数完成对所述文件的操作和处理,然后再进入循环的下一次迭代并使用下一个文件调用它。

function processFiles(files) {
  for (let i = 0; i < files.length; i++) {
    console.log("Loading File into memory");
    loadFileIntoMemory(files[i]);
  }
}

所以它会加载文件 1,等待一切完成,然后加载文件 2。我不希望它在 loadFileIntoMemory 函数中发送垃圾邮件,而不完成前一个文件。

function loadFileIntoMemory(file) {
  
  //create a dictionary using the file name
  originalValues[file.name] = {};
  // create a variable with the file name to pass to storeOriginalValues and replaceOccurence
  var filename = file.name;
  // Start reading the file
  var reader = new FileReader();
  reader.onload = function (file) {
    var arrayBuffer = reader.result;
    // Here we have the file data as an ArrayBuffer.  dicomParser requires as input a
    // Uint8Array so we create that here
    var byteArray = new Uint8Array(arrayBuffer);
    dataSet = dicomParser.parseDicom(byteArray);
    // Store the original values into the dict
    storeOriginalValues(filename);

    // iterate through each metadata field and replace the original value with the de-identified value.
    console.log("De-identifying values")

    for (const [key, value] of Object.entries(elementsToRemove)) {
      var element = dataSet.elements[value];
      if (typeof element !== "undefined") {
        for (var i = 0; i < element.length; i++) {
          dataSet.byteArray[element.dataOffset + i] = 32;
        }
      }
    }

    // Check if the Patient ID is still Present after the de-indentification process is completed
    replaceOccurences(filename, originalValues[filename].PatientID);
    // replaceOccurences(filename, originalValues[filename].PatientName);
    // replaceOccurences(filename, originalValues[filename].etc);

    // download the de-identified DICOM P10 bytestream
    console.log('Downloading File');
    var blob = new Blob([dataSet.byteArray], { type: "application/dicom" });
    var url = window.URL.createObjectURL(blob);
    window.open(url);
    window.URL.revokeObjectURL(url);
    
  };
  reader.readAsArrayBuffer(file);
}

您需要将 loadFileIntoMemory 转换为 Promise。

function loadFileIntoMemory(file) {
    return new Promise((resolve,reject) => { 
        ......
        reader.onload = function (file) {
           ......
           return resolve();  //when all is done, resolve the promise.
        }

    })
}

然后您可以在 async/await 循环中使用该函数。

const processFiles = async (files) => {
  for (let i = 0; i < files.length; i++) {
    console.log("Loading File into memory");
    await loadFileIntoMemory(files[i]);
  }
}