如何等待 fetch api 完成使用 async/await?

How to wait fetch api to finish using async/await?

我有这个 Javascript 程序可以从我的本地服务器加载图像到数据传输,然后使用类型文件将其文件分配到我的输入,但我真的不知道如何等待fetch API 在执行程序的后面部分之前完成。我希望你能帮助我解决我的问题,因为我是初学者。

function image_select(BHID) {
    all_fileBuffer[BHID] = new DataTransfer();
     //add images from database to filebuffer
    setTimeout(async function () {
    $("div#container-"+BHID+" img").each(async function (e) {
        await fetch($(this).attr('src'))
            .then(res => res.blob())
            .then(blob => {
                all_fileBuffer[BHID].items.add(new File([blob], $(this).attr('id'), blob));
            })
        
    }); 
    }, 1000);

    all_attachments[BHID] = document.getElementById("image-" + BHID).files; // <-- reference your file input here

    // append the file list to an array iteratively
    for (let i = 0; i < all_attachments[BHID].length; i++) {
        // Exclude file in specified index
        all_fileBuffer[BHID].items.add(all_attachments[BHID][i]);
    }
    document.getElementById('image-' + BHID).files = all_fileBuffer[BHID].files;
    all_image[BHID] = document.getElementById('image-' + BHID).files;

    all_images[BHID] = [];
    for (i = 0; i < all_image[BHID].length; i++) {
        all_images[BHID].push({
            "name": all_image[BHID][i].name,
            "url": URL.createObjectURL(all_image[BHID][i]),
            "file": all_image[BHID][i],
        })
    }
    document.getElementById('container-' + BHID).innerHTML = "";
    document.getElementById('container-' + BHID).innerHTML = image_show(BHID);
            

console.log(all_fileBuffer[BHID].files); 
}

我不是很明白你的fetch后需要使用哪部分代码,但是多个异步函数是这样处理的

async function main () {
  await Promise.all([1, 2, 3].map(x => 
        new Promise((resolve) => 
          setTimeout(resolve, x*1000)))
  )

  console.log('further code')
}

所以在你的情况下它看起来像这样:

async function imageSelect () {
// ...
    await Promise.all([
        $("div#container-"+BHID+" img").map(async function (e) {
            await fetch($(this).attr('src'))
                .then(res => res.blob())
                .then(blob => all_fileBuffer[BHID].items.add(
                    new File([blob], $(this).attr('id'), blob));
        })
    ]);
    
    console.log('fetch done')
// ...
}