访问Faker图像时出现UnhandledPromiseRejectionWarning错误?

时间:2020-05-22 07:56:19

标签: javascript reactjs es6-promise faker

我是这里的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();

1 个答案:

答案 0 :(得分:0)

您可以添加catch块来处理错误,如下所示:

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));
        })
        .catch((error) => {
          console.log(error);
        });
}