0

我一直在为这段代码苦苦挣扎,我正在寻求帮助。我有一个日期数组,我正在尝试按数组的顺序发出 http 请求并按顺序写入返回信息。

这是我的代码:

const dateArray = ['november-22-2019', 'november-25-2019', 'november-26-2019', 'november-27-2019', 'november-29-2019'];

async function loppThroughArray() {
    for (const date of dateArray) {
        const options = {
            url: process.env.URL + date
        };
        await asyncRequest(options, date);
    }
}

async function asyncRequest(options, date) {
    request(options, function(error, response, html) {
        if (error) {
            return;
        }
        if (response.statusCode !== 200) {
            return;
        }
        const $ = cheerio.load(html);
        const content = $('.entry-content');
        const formattedContent = content.text()
            .split('\t').join('')
            .split('\n\n\n').join('')
            .split('\n\n').join('');
        const dataToBeWritten = '### ' + date + '\n' + formattedContent + '\n\n';
        fs.appendFileSync(`./WODs/${currentDate}.md`, dataToBeWritten, 'utf-8', {'flags':'a+'});
        fs.appendFileSync(`./WODs/${currentDate}.txt`, dataToBeWritten, 'utf-8', {'flags':'a+'});
    });
}

loppThroughArray();

4

1 回答 1

0

我设法通过使用使用承诺而不是回调的“请求”版本来解决这个问题。见代码:

async function loppThroughArray() {
    for (const date of dateArray) {
        const options = {
            url: process.env.URL + date
        };
        await asyncRequest(options, date);
        console.log('fetching: ', date);
    }
}

async function asyncRequest(options, date) {
    await rp(options)
        .then(function(html){
            const $ = cheerio.load(html);
            const content = $('.entry-content');
            const formattedContent = content.text()
            .split('\t').join('')
            .split('\n\n\n').join('')
            .split('\n\n').join('');
            const dataToBeWritten = '### ' + date + '\n' + formattedContent + '\n\n';
            fs.appendFileSync(`./WODs/${currentDate}.md`, dataToBeWritten, 'utf-8', {'flags':'a+'});
            fs.appendFileSync(`./WODs/${currentDate}.txt`, dataToBeWritten, 'utf-8', {'flags':'a+'});
        });
}

loppThroughArray();

于 2019-12-01T14:15:47.853 回答