Javascript Node.js";fs.writeFile();Promise.all内部的回调在Promise.all解析后执行
在使用Promise.all编写了一堆文件之后,我正在尝试记录一些东西。但不知何故,数组中的最后一个文件总是在Promise.all解决后调用 请参阅下面的代码和输出Javascript Node.js";fs.writeFile();Promise.all内部的回调在Promise.all解析后执行,javascript,node.js,asynchronous,promise,async-await,Javascript,Node.js,Asynchronous,Promise,Async Await,在使用Promise.all编写了一堆文件之后,我正在尝试记录一些东西。但不知何故,数组中的最后一个文件总是在Promise.all解决后调用 请参阅下面的代码和输出 Promise.all(videos.map(async (video) => { const dest = `${destinationFolder}/${video.name}`; const response = await fetch(video.url);
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}`);
});
预期产出:
✔ Downloaded video: video1.mp4 to ./dest/video1.mp4
✔ Downloaded video: video2.mp4 to ./dest/video2.mp4
✨ Downloaded all videos to ./dest
实际产量:
✔ Downloaded video: video1.mp4 to ./dest/video1.mp4
✨ Downloaded all videos to ./dest
✔ Downloaded video: video2.mp4 to ./dest/video2.mp4
fs.writeFile
使用回调返回结果,但不返回承诺。
您可以使用newpromise
将此回调调用转换为异步调用
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;
要使用
await
,您需要返回承诺的函数版本,此版本位于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}`);
});
writeFile
接受回调,但不返回承诺。您不能等待它。使用fs.promise
谢谢,这个解决方案很有效,但我更喜欢上面提到的@z1ne2wo现有的解决方案。