【发布时间】:2020-09-09 00:21:47
【问题描述】:
我在这里学习 JavaScript。我有一个名为 downloadFakeImage.js 的文件,其脚本如下:
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const url = [];
// Generate 1000 fake url from faker
for (let i=0; i<1000; i++) {
url.push(faker.image.fashion());
}
// Download 1000 user photos to local image folder
for (let i=0; i<url.length; i++) {
// path for image storage
const imagePath = path.join(__dirname, './image', `${i}.jpg`);
axios({
method: 'get',
url: url[i],
responseType: 'stream'
})
.then((response) => {
response.data.pipe(fs.createWriteStream(imagePath));
});
}
此脚本的目标是生成 1000 张假时尚图像到名为 image 的文件夹中。当我在终端中运行node downloadFakeImage.js 时,只有一些图像可以保存到文件夹中。我的终端显示以下错误消息的全部早午餐:
Error message from the terminal that I received
我认为这可能与异步问题有关,有人可以教我如何折射我的脚本以使其工作吗?
更新:
我将代码重构为以下内容,并且能够生成一些图像,但仍然无法生成 1000 个图像。对于前 300 张图像,它运行正常,然后失败了。
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
async function seedImage() {
const url = [];
// Generate 1000 fake url from faker
for (let i = 0; i < 1000; i++) {
url.push(faker.image.fashion());
}
// Download 1000 user photos to local image folder
for (let i = 0; i < url.length; i++) {
// path for image storage
const imagePath = await path.join(__dirname, './image', `${i}.jpg`);
axios({
method: 'get',
url: url[i],
responseType: 'stream'
})
.then((response) => {
response.data.pipe(fs.createWriteStream(imagePath));
})
.catch((error) => {
console.log(error);
});
}
}
seedImage();
【问题讨论】:
-
向 Promise 链添加一个
catch回调,对被拒绝的 Promise 错误执行任何操作,或者放弃并忽略它。这回答了你的问题了吗? What is an unhandled promise rejection? -
这能回答你的问题吗? What is an unhandled promise rejection?
-
您确实意识到您正在尝试同时发出 1000 个请求,对吗?也许端点在说“没办法”,并给你错误,你没有抓住
-
我能够使用下面的帮助发现错误。但是,我无法通过阅读错误来弄清楚如何解决这个问题。可能是我的脚本没有正确编写。我可能不得不学习如何使用 Unsplash API。
标签: javascript reactjs es6-promise faker