繁体   English   中英

等待不等待异步 function

[英]Await not awaiting async function

我正在为 api 开发一个 webscraper,我试图将它划分为功能,无论出于何种原因等待都没有等待 promise 被实现

const PORT = 8000
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())

const clarinURL = 'https://www.clarin.com/economia/'

app.get('/', function (req, res) {
    res.json('This is my webscraper')
})

app.get('/results', async (req, res) => {
    let results = await cheerioPick(clarinURL, '.content-nota', 'h2', 'a', 'https://www.clarin.com')
    console.log(results)
    res.send(results)
})

async function cheerioPick(url, container, titletag, urltag, domain) {
    axios(url)
    .then(response => {
        const html = response.data
        const $ = cheerio.load(html)
        const articles = []

        $(container, html).each(function () { //<-- cannot be a function expression
            const title = $(this).find(titletag).text()
            const url = domain + $(this).find(urltag).attr('href')
            articles.push({
                title,
                url
            })
        })
        console.log("articles")
        return articles
    })
    .catch(err => console.log(err))
}

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))

在控制台上打印:

undefined
articles

所以它显然没有等待异步 function 返回它的结果

问题是 function cheerioPick没有返回Promise

有一些方法可以完成这项工作。 我建议在您的 axios 段中使用 async/await,以便您的整个代码使用与异步编码相同的方法。

async function cheerioPick(url, container, titletag, urltag, domain) {
  try {
    const response = await axios(url);
    const html = response.data
    const $ = cheerio.load(html)
    const articles = []

    $(container, html).each(function () { //<-- cannot be a function expression
        const title = $(this).find(titletag).text()
        const url = domain + $(this).find(urltag).attr('href')
        articles.push({
            title,
            url
        })
    })
    console.log("articles")
    return articles
  } catch (err) {
    console.log(err)
  }
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM