Search code examples
javascriptnode.jsimageasync-awaitdownload

How can I wait for an image to download Javascript?


Using Nodejs and image-downloader. I am trying to run a compiler function at the end after all the images have downloaded. The imageDownload function gets triggered multiple times. The console.log('Saved to', filename); runs way after everything.

import {image} from 'image-downloader';
await imageDownload ('https://syntheticnews.com/wpcontent/uploads/2023/12/Kodiak_Defense_1-1024x683.jpg');

export async function imageDownload (url) {
  var options={
    url: url,
    dest: `../../testimage.jpg`,  
  };
        
  image(options)
    .then(({ filename }) => {
      console.log('Saved to', filename);     
    })
    .catch((err) => console.error(err));
}

console.log ("This will be the next function and should run after the save to filename log");

The await on the function call just seems to await the running of the code not the downloading of the file. I really need an await on the .then statement but that doesn't work :). Is there a better way than watching the folder and await the files expected?


Solution

  • await waits for promises to be resolved or rejected. In the above code, the image function returns a promise but the wrapper function imageDownload is not returning the promise returned by the image function.

    Read this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    Try this code -

    import { image } from 'image-downloader';
    await imageDownload('https://syntheticnews.com/wpcontent/uploads/2023/12/Kodiak_Defense_1-1024x683.jpg');
    
    export async function imageDownload(url) {
        var options = {
            url: url,
            dest: `../../testimage.jpg`,
        };
    
        return image(options)
            .then(({ filename }) => {
                console.log('Saved to', filename);
            })
            .catch((err) => console.error(err));
    }
    
    console.log("This will be the next function and should run after the save to filename log");
    

    Although above code works, I would recommend not using await directly in a file - Using await outside of an async function