javascript - 该函数不会在 JavaScript 的另一个函数中调用

我遇到了一个完全无法理解的在函数内部调用函数的行为。 当我在 fs.writeFile 之后在 runParser() 中调用 telegram() 函数时,它就不起作用了。但是如果我在 runParser() 函数之外执行它,它就可以正常工作。也就是说,我有一个 log() 函数,它给我一个带有文本的 console.log。有用。为什么会这样,我可以在函数内部调用它吗?另外,我注意到如果我将函数放在 try block 的开头,它就可以工作。

   const puppeteer = require('puppeteer');
const fs = require('fs');
const url = 'https://rezka.ag/films/page/';
const watched = '/?filter=watching';
const telegram = require('./telegram.js')
const {Bot} = require("tgapi");
const log=require('./log')

////дата
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0')
let yyyy = today.getFullYear();
today = mm + dd + yyyy;
////
let runParser = async () => {
    let flag = true
    let itog = []
    let counter = 1
    let browser = await puppeteer.launch({
        headless: true,
        slowMo: 100,
        devtools: true
    })
    try {
        let page = await browser.newPage()
        await page.setViewport({width: 1400, height: 900})
        while (flag) {
            await page.goto(`${url}${counter}${watched}`)
            await page.waitForSelector('div.b-footer__right')
            let html = await page.evaluate(async () => {
                let page = []
                try {
                    let divs = document.querySelectorAll('div.b-content__inline_item')
                    divs.forEach(div => {
                        let a = div.querySelector('#main > div.b-container.b-content.b-wrapper > div.b-content__inline > div > div.b-content__inline_items > div > div.b-content__inline_item-link > a')
                        let obj = {
                            link: a.href,
                            title: a.innerText,
                            info: div.querySelector('#main > div.b-container.b-content.b-wrapper > div.b-content__inline > div > div.b-content__inline_items > div> div.b-content__inline_item-link > div').innerText
                        }
                        page.push(obj)
                    })

                } catch (e) {

                    console.log(e)
                }
                return page

            }, {waitUntil: 'div.b-footer__right'})
            itog.push(html)
            console.log(itog)
            for (let i = 0; i < counter; i++) {
                if (counter === 5) {
                    flag = false
                }
            }
            counter++

        }
        await browser.close()
        fs.writeFile(`movie ${today}.json`, JSON.stringify({data: itog}), err => {
            if (err) throw err
            console.log('saved')
        })
telegram(today)

        log()
    } catch (e) {
        console.log(e)
        await browser.close()
    }
    return  JSON.stringify(itog)
}


module.exports = runParser

telegram.js

const {Bot} = require("tgapi");
const fs = require("fs");

const telegram =  function  (today) {
    const bot = new Bot('TOKEN')
    const chat_id = 123456
    const document = fs.createReadStream(`movie ${today}.json`)
    bot
        .sendDocument({chat_id, document})
        .then(console.log)

}

module.exports = telegram

log.js

  function log(){
    console.log("work well")
}
module.exports=log

最佳答案

显然,您的 telegram 函数包含一些异步代码。至少这是我根据调用 sendDocument

后的 then 回调所做的猜测

如果这是正确的,您应该返回 promise 并在 telegram 调用前使用 await

另外,您使用 fs.writeFile,它是异步的但不返回 promise (它使用回调参数)。由于您在 telegram 函数中使用了文件内容,因此我建议改用 fs.promises.writeFile 并等待其完成。

内部函数 runParser

await browser.close()
await fs.promises.writeFile(`movie ${today}.json`, JSON.stringify({data: itog}))
console.log('saved')
await telegram(today)
log()

telgram.js

const {Bot} = require("tgapi");
const fs = require("fs");

const telegram =  function  (today) {
  const bot = new Bot('TOKEN')
  const chat_id = 123456
  const document = fs.createReadStream(`movie ${today}.json`)
  return bot
    .sendDocument({chat_id, document})
    .then(console.log)
}

module.exports = telegram

更一般地说,当在 OK/KO 情况下移动一些代码时,这通常意味着某处存在一些异步问题。

https://stackoverflow.com/questions/71302843/

相关文章:

rest - Keycloak 返回未经授权的 401

typescript - 如何使用带有更新的 FirestoreDataConverter?

ruby-on-rails - Rails 7 升级后的 ActionController::Unk

reactjs - 使用 useEffect 监听子组件可以吗?

telegram - 热门从 Telegram Bot 消息中获取回调数据

python-3.x - SSHTunnel 搜索默认私钥 (id_rsa) 而不是我指定的 ssh

javascript - 为什么 Jest 在 node-fetch 上失败,在导入时给出语法错误

sql - 如何在 Snowflake 中嵌套使用一个流的存储过程?

angular - 将 Angular 12 升级到 13 - mjs 文件中的编译错误

cypress - 使用 Cypress 运行测试时,在 Auth0 中禁用验证码的正确方法是什么