来自同步函数(Node.js)的异步函数调用

时间:2020-05-14 01:55:31

标签: javascript node.js asynchronous puppeteer

我无法从异步函数访问响应。我知道这是一个常见问题,但是找不到与我的问题有关的另一个问题。

我的同步功能:

const output = getSeasons.getSeasons('*URL*', (data)=>{
        return data
    })
  console.log(data)

我的异步功能:

const getSeasons = async (url, callback) => {

     seasonTitle = *ASYNCHRONOUS CALL THAT RETURNS AN ARRAY*

        await seasonTitle
        callback(seasonTitle) 
}

我的问题是我希望能够在以后的行中利用“输出”继续执行我的同步功能。我能想到的唯一解决方案是:

const output = getSeasons.getSeasons('*URL*', (data)=>{
            return data
        }).then(()=>{  console.log(data)  }

此选项的问题是,我以后针对该功能的所有代码都必须写在“ .then”功能内。我更希望在继续执行同步功能之前先等待响应,而不将所有内容都放入“ .then”。主要是因为我将有多个调用异步函数的函数,这将导致多个嵌套的“ .then”函数。

编辑:

这是实际的代码,异步调用正在搜寻具有季节类的元素,然后我尝试返回该数组:

const output = getSeasons.getSeasons('https://www.rocketleagueesports.com/schedule/', (data)=>{
        console.log(data)
    })

    console.log(output)


const getSeasons = async (url, callback) => {

    const browser = await puppeteer.launch({ headless: true })
    const page = await browser.newPage()
    await page.goto(url)
    await page.waitForSelector('.match') //Waits for elements with class "match" to load before executing further


        const seasonTitle = page.evaluate(() => {
            const seasonTitleArray = Array.from(document.querySelectorAll('.sub-header .scoreboard-container .container-lg .show-on-md .select-options-container .seasons li'))
            return seasonTitleArray.map(li => li.textContent)
        })

        await seasonTitle 
        callback(seasonTitle)

}

2 个答案:

答案 0 :(得分:0)

为什么不像在 getSeasons

中那样使用 await
const getSeasons = async funciton(url) {
   return await *ASYNCHRONOUS CALL THAT RETURNS AN ARRAY*
}

(async () => {
  const output = await getSeasons.getSeasons('*URL*')
  console.log(output)
})()

async/await

答案 1 :(得分:0)

如果您不想在then块中编写代码,请使用async/await

async someFunction() {
    const output = await getSeasons.getSeasons(...)
}

除此之外,您的getSessions还需要改进。为什么同时需要回调和async来返回Promise?

尝试重构如下内容:

const getSeasons = async function(url) {
   return *ASYNCHRONOUS CALL THAT RETURNS AN ARRAY*
}