简体   繁体   English

Node.js Promise.all 内的“fs.writeFile()”回调在 Promise.all 已解决后执行

[英]Node.js "fs.writeFile()" callback inside of Promise.all executes after Promise.all has resolved

I am trying to log something after a bunch of files have been written using Promise.all.在使用 Promise.all 编写了一堆文件后,我试图记录一些东西。 But somehow the last file in my array always calls back after the Promise.all has resolved.但不知何故,我数组中的最后一个文件总是在 Promise.all 解析后回调。

Please see the code & output below.请参阅下面的代码 & output。

Promise.all(videos.map(async (video) => {
            const dest = `${destinationFolder}/${video.name}`;
            const response = await fetch(video.url);
            const buffer = await response.buffer();
            await fs.writeFile(dest, buffer, () => {
                console.log(`✔ Downloaded video: ${video.name} to ${dest}`);
            });
        }
    )).then(() => {
        console.log(`✨ Downloaded all videos to ${destinationFolder}`);
    });

Expected output:预计 output:

✔ Downloaded video: video1.mp4 to ./dest/video1.mp4
✔ Downloaded video: video2.mp4 to ./dest/video2.mp4
✨ Downloaded all videos to ./dest

Actual output:实际 output:

✔ Downloaded video: video1.mp4 to ./dest/video1.mp4
✨ Downloaded all videos to ./dest
✔ Downloaded video: video2.mp4 to ./dest/video2.mp4

To use await , you need a version of the function that returns a Promise, this version is in the promises namespace:要使用await ,您需要一个返回 Promise 的 function 版本,这个版本位于promises命名空间中:

Promise.all(videos.map(async (video) => {
    const response = await fetch(video.url);
    const destination = `${folder}/${video.name}`;
    await fs.promises.writeFile(destination, await response.buffer());

    console.log(`✔ Downloaded video: ${video.name} to ${destination}`);
)).then(() => {
    console.log(`✨ Downloaded all videos to ${folder}`);
});

fs.writeFile uses callback to return a result and it doesn't return Promise. You can use new Promise to convert this call with a callback into async call. fs.writeFile使用回调返回结果,它不返回 Promise。您可以使用new Promise将此调用与回调转换为异步调用。

const writeFilePromise = new Promise((resolve, reject) => {
  fs.writeFile(dest, buffer, (err) => {
                if (err) {
                  reject(err)
                }
                console.log(`✔ Downloaded video: ${video.name} to ${dest}`);
                resolve()
            });
});
await writeFilePromise;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM