我对promise 很陌生,并试图让Promises.All在这种情况下发挥作用. 然而,当我try 通过调用changeFile函数来运行代码时,它会立即到达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);
        });
}

推荐答案

您的代码有两个问题.

  1. 您不会在processDoc函数return await fetch中返回fetch结果.
  2. 您需要调用数组参数Promise.all内的函数来等待这些promise await Promise.all([processDoc1(), processDoc2()]).
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);
        });
}

Javascript相关问答推荐

Vue.js使用特定索引值的数据更新html

我应该如何在此Angular 16应用程序中的方法中使用@ Hostspel?

Webpack将懒惰加载的模块放入主块中

如何从defineExpose访问数据和方法

React状态变量在使用++前置更新时引发错误

在JS中获取名字和姓氏的首字母

按钮未放置在html dis位置

如何在RTK上设置轮询,每24小时

在vercel throws上部署带有gunjs的sveltekit应用无法找到模块./' lib/文本编码'

嵌套异步JavaScript(微任务和macrotask队列)

html + java script!需要帮助来了解为什么我得到(无效的用户名或密码)

使用ThreeJ渲染的形状具有抖动/模糊的边缘

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

如何在JAVASCRIPT中临时删除eventListener?

不同表的条件API端点Reaction-redux

P5.js中的分形树

判断函数参数的类型

自动滚动功能在当前图像左侧显示上一张图像的一部分

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

在JavaScript中将Base64转换为JSON