我对 Promises 很陌生,并试图让 Promises.all 在这种情况下工作。但是,当我尝试通过调用 processFiles 函数来运行代码时,它会立即命中 Promises.all then 方法中的 console.log 行。我做错了什么?
let doc1Text = "";
let doc2Text = "";
const processDoc = async (fileInput) => {
var input = document.getElementById(fileInput);
await fetch(urls.GetContractLanguageText, {
method: 'POST',
body: input.files[0]
})
.then(j => j.json())
.then(x => {
return x.ConvertedText;
});
}
const processDoc1 = async () => {
$(selectors.fileProgress1).val(0);
doc1Text = await processDoc(selectors.baseFile);
$(selectors.fileProgress1).val(100);
};
const processDoc2 = async () => {
$(selectors.fileProgress2).val(0);
doc1Text = await processDoc(selectors.newFile);
$(selectors.fileProgress2).val(100);
};
const processFiles = async () => {
$(selectors.aiComparison).removeClass(selectors.hide);
await Promise.all([processDoc1, processDoc2])
.then(() => {
console.log(doc1Text, doc2Text);
});
}
您的代码有两个问题。
fetch
函数中返回 processDoc
结果。Promise.all
数组参数内的函数来等待这些 Promise。let doc1Text = "";
let doc2Text = "";
const processDoc = async (fileInput) => {
var input = document.getElementById(fileInput);
return await fetch(urls.GetContractLanguageText, {
method: 'POST',
body: input.files[0]
})
.then(j => j.json())
.then(x => x.ConvertedText);
}
const processDoc1 = async () => {
$(selectors.fileProgress1).val(0);
doc1Text = await processDoc(selectors.baseFile);
$(selectors.fileProgress1).val(100);
};
const processDoc2 = async () => {
$(selectors.fileProgress2).val(0);
doc2Text = await processDoc(selectors.newFile);
$(selectors.fileProgress2).val(100);
};
const processFiles = async () => {
$(selectors.aiComparison).removeClass(selectors.hide);
await Promise.all([processDoc1(), processDoc2()])
.then(() => {
console.log(doc1Text, doc2Text);
});
}