我想讓一個功能等待另一個功能完全完成。我們有這個函式處理檔案串列并將每個檔案加載到 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);
}
uj5u.com熱心網友回復:
您需要將您的 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]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471410.html
標籤:javascript 功能 异步 等待
上一篇:在期待[CertificateRequest]時收到ServerHelloDone握手訊息
下一篇:使用Bash在CSV中過濾月份
