NodeJS 如何等待图像下载JavaScript?

nhhxz33t  于 9个月前  发布在  Node.js
关注(0)|答案(1)|浏览(105)

使用Nodejs和image-downloader。我试图在所有图像下载完毕后运行一个编译器函数。imageDownload函数被多次触发。console.log('Saved to',filename);在所有操作之后运行。

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

字符串
函数调用中的await似乎只是等待代码的运行而不是文件的下载。我真的需要在.then语句中使用await,但这不起作用:)。还有比监视文件夹并等待预期文件更好的方法吗?

isr3a4wc

isr3a4wc1#

await等待promise被解析或拒绝。在上面的代码中,image函数返回一个promise,但 Package 器函数imageDownload没有返回image函数返回的promise。
阅读-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
试试这个代码-

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

字符串
虽然上面的代码可以工作,但我建议不要在文件Using await outside of an async function中直接使用await

相关问题