gpt4 book ai didi

javascript - JS返回不等待await

转载 作者:行者123 更新时间:2023-12-03 01:37:56 24 4
gpt4 key购买 nike

我正在尝试使用异步等待。

我的应用程序是这样启动的

axios.get(`${ROOT_URL}/ccidxann.php`)
.catch(err => console.error('axios error get', err))
.then(async res => {
const html = res.data
const jobList = await getJobList(html)
console.log(' after each jobList', jobList)
// jsonfile.writeFileSync('jobs.json', jobList, { flag: 'a' })
})
.catch(err => console.error(err))

问题是 jobList始终作为空数组返回。这是getJobList功能

async function getJobList (html) {
const jobList = []

const dom = new JSDOM(html)
const { window } = dom
const $ = require('jquery')(window)
const jobsInDom = $('table').first().find('td > a')

// AWAIT HERE
await jobsInDom.each(async function (index, jobElem) {
const name = $(jobElem).text()
const url = $(jobElem).attr('href')
// Another AWAIT HERE
const jobDetailsHTML = await getJobDetailsHTML(`${ROOT_URL}/${url}`)
.catch(err => console.error('getJobDetailsHTML err', err))
const domDetails = new JSDOM(jobDetailsHTML)
const { window: windowDetails } = domDetails
const $details = require('jquery')(windowDetails)
const jobDetailsHTMLBody = $details('body').prop('outerHTML')
jobList.push({
_id: url,
name,
detailsHTML: jobDetailsHTMLBody
})
console.log('in each jobList', jobList)
}) //each
return jobList
}

正如你所看到的,我输入了 async前面的关键字,

我已经输入了 async each回调中的关键字

并输入await在所有异步操作之前。

console.logeach的回调中打印填充有值的数组

但似乎returneach 之前工作

即使有await前面有关键字。

这里还有getJobDetailsHTML万一。这是一个简单的功能,而且似乎工作得很好

async function getJobDetailsHTML (url) {
// ANOTHER AWAIT HERE
return await axios.get(url).data
}

最佳答案

我认为jobsInDom.each是同步函数,因此在前面放置await不会给您带来预期的效果。因此,您需要以某种方式获得在所有作业处理完成后解决的 promise ,如下所示:

  // handles one element and returns promise
const jobHandler = async jobElem => {
const name = $(jobElem).text()
const url = $(jobElem).attr('href')
const jobDetailsHTML = await getJobDetailsHTML(`${ROOT_URL}/${url}`)
.catch(err => console.error('getJobDetailsHTML err', err))
const domDetails = new JSDOM(jobDetailsHTML)
const { window: windowDetails } = domDetails
const $details = require('jquery')(windowDetails)
const jobDetailsHTMLBody = $details('body').prop('outerHTML')
jobList.push({
_id: url,
name,
detailsHTML: jobDetailsHTMLBody
})
console.log('in each jobList', jobList)
}

const promises = [];

// start processing of each element
jobsInDom.each((index, jobElem) => promises.push(jobHandler(jobElem));

// wait for processing of all job elements
await Promise.all(promises);

关于javascript - JS返回不等待await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50985577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com