我如何解决UnhandledPromiseRejectionWarning:错误:读取ETIMEDOUT和UnhandledPromiseRejectionWarning:错误:写入EPROTO错误

问题描述 投票:0回答:1

我正在使用axios和cheerio进行一些网络抓取。我很确定我将for循环写错了。关于使其异步的东西。但是我最近开始学习,我不明白那意味着什么。我可能也完全错了。

for (let i = 0; i < list.length; i++) {
    axios.get(list[i].link).then((res) => {
        const $ = cheerio.load(res.data);
        var name = $('.header').find('.itemprop').text()
        $('.knownfor-title').each((i, el) => {
            var movie = $(el).find('img').attr('src')
            var title = $(el).find('img').attr('title')
            var link = 'https://www.imdb.com' + $(el).find(".knownfor-title-role").find('a').attr('href')

            var data = {
                name,
                movie,
                title,
                link
            }
            writeStream.write(`${name}, ${movie}, ${title}, ${link} \n` ); 
            console.log(data)
        })  
    })
}

这是我得到的错误

(node:5293) UnhandledPromiseRejectionWarning: Error: read ECONNRESET
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27)


(node:5293) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 512)


(node:5293) UnhandledPromiseRejectionWarning: Error: read ETIMEDOUT
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27)
(node:5293) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 420)

您明白了

javascript node.js axios cheerio
1个回答
0
投票

这应该是axios使用.then()和.catch()的语法

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
© www.soinside.com 2019 - 2024. All rights reserved.