Javascript 在等待异步函数后运行同步调用
我正在编写一个NodeJS程序,如下所示。此代码的目的是从一个API的多个页面进行解析(页面数量可变,因此会刮取第一个页面以查看要刮取的页面数量),然后将所有页面上载到MongoDB,然后使用另一个文件中的函数“分析页面”(操纵关键字): 我尝试使用以下方法:Javascript 在等待异步函数后运行同步调用,javascript,mongodb,Javascript,Mongodb,我正在编写一个NodeJS程序,如下所示。此代码的目的是从一个API的多个页面进行解析(页面数量可变,因此会刮取第一个页面以查看要刮取的页面数量),然后将所有页面上载到MongoDB,然后使用另一个文件中的函数“分析页面”(操纵关键字): 我尝试使用以下方法: collection.insertMany(ah) await collection.insertMany(ah) manipulate.AHdata 但它不工作,因为。。。 你知道我能做什么吗 谢谢你的帮助,祝你度过愉快的一天 继我所
collection.insertMany(ah)
await collection.insertMany(ah)
manipulate.AHdata
但它不工作,因为。。。
你知道我能做什么吗
谢谢你的帮助,祝你度过愉快的一天 继我所有的评论和观点之后,以下是我认为更好(但显然未经测试)的代码版本:
const MongoClient = require('mongodb').MongoClient
const fetch = require('node-fetch')
const config = require('./config.json')
const manipulate = require('./manipulateDB')
let auctionCollection
async function getAuctionPage(page = 0) {
try {
const response = await fetch(`https://website.net/page/${page}`)
const data = await response.json()
return data
} catch (err) {
console.error("Faced an error: " + err)
}
}
async function getFullAH() {
try {
let ah = []
let firstPage = await getAuctionPage(0)
for (let i = 1; i <= firstPage.totalPages; i++) {
const page = await getAuctionPage(i);
for (let auction of page.auctions) ah.push(auction);
}
return ah
} catch (e) {
console.log('Failed to update auctions', e)
return
}
}
async function main() {
let startTime = Date.now()
let ah = await getFullAH()
let timeTaken = Date.now() - startTime
auctionCollection.drop()
auctionCollection.insertMany(ah)
console.log(`Auction update complete in ${timeTaken} ms ${Date().toLocaleString()}`)
console.log("Starting analysis")
await auctionCollection.insertMany(ah)
manipulate.printAHInfos()
// This essentially is the delay instead of every 60000 ms
setTimeout(main, 60000 - timeTaken)
}
async function connectToDB() {
console.log('Connecting to db...')
let db
try {
db = await MongoClient.connect(
config.mongoSRV,
{ useNewUrlParser: true, useUnifiedTopology: true });
} catch (err) {
return connectToDB()
}
auctionCollection = db.collection('auctions');
console.log('Successful connection to database')
main() // You don't need hacks and verifications to check if the DB is connected. If there was a problem, it got caught in the catch()
}
connectToDB()
const MongoClient=require('mongodb')。MongoClient
const fetch=require('node-fetch')
const config=require(“./config.json”)
const mobile=require('./mobiledb')
让拍卖收藏
异步函数getAuctionPage(page=0){
试一试{
const response=等待获取(`https://website.net/page/${page}`)
const data=wait response.json()
返回数据
}捕捉(错误){
console.error(“遇到错误:+err”)
}
}
异步函数getFullAH(){
试一试{
让ah=[]
让第一页=等待getAuctionPage(0)
对于(让i=1;我可以看到实际代码而不是伪代码?还有什么“”?@JeremyThille添加了我的代码而不是伪代码。好的,谢谢。你还没有说什么不起作用,但无论如何,我看到了这段代码的几个问题。1.startAHLoop()
被标记为async
,这是无用的,因为您没有等待它中的任何内容,您只是定义了其他函数。这很奇怪,您可能想为此使用一个类。2.在for
循环中,您正在执行getAuctionPage(i)。然后(
而不是等待getAuctionPage(i)
。因此,所有fetch
操作都同时启动,所有.then()
稍后将被触发,这迫使您在进行黑客攻击时执行此操作。我尝试使用以下命令:“-呃,不要调用collection.insertMany(啊)
两次?调用一次,然后等待结果。3.你也应该等待MongoClient.connect()
而不是这个,同时
再次破解。至少使用回调函数…4.数据。收集('auctions')
数据
未定义,不知道这是什么。5.skyblock=DB.DB('skyblock')
不知道什么是skyblock
,你没有在任何地方使用它。6.if(typeof ah.ok=='undefined')
如何定义ah.ok
数组?ah
感谢您的反馈。我非常喜欢您在getFullAH函数中的输入,因为它简化了很多。另一方面,在解决了一些问题后,操纵.printAHInfos()在数据库上载到MongoDB之前被调用。知道如何修复吗?数据库上载到MongoDB
实际上没有任何意义,因为MongoDB是一个数据库,您无法将数据库上载到数据库。现在我不知道为什么会发生这种情况,因为我不知道您写了什么:)我的代码似乎是正确的,我正在等待insertMany
,所以这里没有问题。我的意思是在运行代码时(甚至在连接到MongoDB之前)首先调用Operate.printAHInfos()
等待也无济于事。好吧,我怀疑我的代码可能会发生这种情况。我检查了它,它似乎是对的。因为我不知道你做了什么更改,也不知道你做了什么,把我的代码和你的代码合并在一起,我无法知道发生了什么。也许你保留了一些。然后()
那会把一切都搞砸,我不知道。我想我已经明白了问题所在。这是一个开始。const-mobile=require('./mobiledb')
在脚本运行之前加载。因此,我没有使用单独的文件,而是在同一个文件中使用了一个新类,这样它就不会运行了。
collection.insertMany(ah)
await collection.insertMany(ah)
manipulate.AHdata
const MongoClient = require('mongodb').MongoClient
const fetch = require('node-fetch')
const config = require('./config.json')
const manipulate = require('./manipulateDB')
let auctionCollection
async function getAuctionPage(page = 0) {
try {
const response = await fetch(`https://website.net/page/${page}`)
const data = await response.json()
return data
} catch (err) {
console.error("Faced an error: " + err)
}
}
async function getFullAH() {
try {
let ah = []
let firstPage = await getAuctionPage(0)
for (let i = 1; i <= firstPage.totalPages; i++) {
const page = await getAuctionPage(i);
for (let auction of page.auctions) ah.push(auction);
}
return ah
} catch (e) {
console.log('Failed to update auctions', e)
return
}
}
async function main() {
let startTime = Date.now()
let ah = await getFullAH()
let timeTaken = Date.now() - startTime
auctionCollection.drop()
auctionCollection.insertMany(ah)
console.log(`Auction update complete in ${timeTaken} ms ${Date().toLocaleString()}`)
console.log("Starting analysis")
await auctionCollection.insertMany(ah)
manipulate.printAHInfos()
// This essentially is the delay instead of every 60000 ms
setTimeout(main, 60000 - timeTaken)
}
async function connectToDB() {
console.log('Connecting to db...')
let db
try {
db = await MongoClient.connect(
config.mongoSRV,
{ useNewUrlParser: true, useUnifiedTopology: true });
} catch (err) {
return connectToDB()
}
auctionCollection = db.collection('auctions');
console.log('Successful connection to database')
main() // You don't need hacks and verifications to check if the DB is connected. If there was a problem, it got caught in the catch()
}
connectToDB()