Node.js中使用image-downloader等待图片下载完成的方案问询
解决image-downloader下载完成后再执行后续代码的问题
你的问题核心是imageDownload函数虽然标记了async,但内部没有返回图片下载操作的Promise,导致外部的await只能等待函数执行结束,无法等待异步下载完成。下面是两种优化实现方式:
方式一:返回Promise链
修改imageDownload函数,让它返回image()方法的Promise链,这样外部的await就能正确等待下载完成:
import { image } from 'image-downloader'; // 注意:await必须在async函数环境中执行,这里用自执行async函数包裹 (async () => { await imageDownload('https://syntheticnews.com/wpcontent/uploads/2023/12/Kodiak_Defense_1-1024x683.jpg'); console.log("This will be the next function and should run after the save to filename log"); })(); export async function imageDownload(url) { const options = { url: url, dest: `../../testimage.jpg`, }; // 返回Promise,让外部await可以等待下载完成 return image(options) .then(({ filename }) => { console.log('Saved to', filename); }) .catch((err) => { console.error(err); throw err; // 抛出错误,方便外部捕获处理 }); }
方式二:内部用async/await改写
把函数内部的Promise链式调用改成async/await写法,代码更直观:
import { image } from 'image-downloader'; (async () => { try { await imageDownload('https://syntheticnews.com/wpcontent/uploads/2023/12/Kodiak_Defense_1-1024x683.jpg'); console.log("This will be the next function and should run after the save to filename log"); } catch (err) { console.error(err); } })(); export async function imageDownload(url) { const options = { url: url, dest: `../../testimage.jpg`, }; // 内部await下载操作,函数会自动返回Promise const { filename } = await image(options); console.log('Saved to', filename); }
批量下载多张图片
如果需要多次调用imageDownload下载多张图片,之后再执行编译函数,可以用Promise.all等待所有下载完成:
import { image } from 'image-downloader'; (async () => { const imageUrls = [ 'https://example.com/img1.jpg', 'https://example.com/img2.jpg', 'https://example.com/img3.jpg' ]; // 等待所有图片下载完成 await Promise.all(imageUrls.map(url => imageDownload(url))); // 所有下载完成后执行编译函数 runCompileFunction(); })(); export async function imageDownload(url) { const options = { url: url, dest: `../../test-${Date.now()}.jpg`, // 注意批量下载要修改文件名避免覆盖 }; const { filename } = await image(options); console.log('Saved to', filename); } function runCompileFunction() { // 这里写你的编译逻辑 console.log('开始执行编译操作'); }
内容的提问来源于stack exchange,提问作者SyntheticTV
相关产品推荐
相关产品推荐

