Promise.all 立即跳转到 then 而不是调用所有的 Promise

问题描述 投票:0回答:1

我对 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);
        });
}
javascript es6-promise
1个回答
0
投票

您的代码有两个问题。

  1. 您不会在
    fetch
    函数中返回
    processDoc
    结果。
  2. 您需要调用
    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);
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.