Search code examples
javascriptfetch-apidata-transfer

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


I have this Javascript program that will load images from my local server to datatransfer, then assign its files to my input with type file, but I really don't have an idea on how to wait for the fetch API to finish before executing the later part of the program. I'm hoping you can help me with my problem because I'm a beginner.       

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); 
}

Solution

  • I don't quite understand what part of code you need to use after your fetch, but multiple async functions are handled like this

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

    So in your case it would look something like this:

    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')
    // ...
    }