在 while 循环中多次调用函数
我正在尝试从函数调用中获取数据,并将其保留在 while 循环中,这样如果未收到数据,该函数将被一次又一次地调用。我对数据的意思是我从 getData 函数返回的 data1、data2 和 data3 数组应该被填充并且不具有空值。但我无法找到解决方案。
这是我的代码:
router.get('/someurl' , async(req,res) => {
let data = [];
while(data.length == 0)
{
data = await functionCall()
console.log(data)
}
})
这是我的 functionCall 代码的格式:
const unirest = require("unirest");
const cheerio = require('cheerio')
const getData = async() => {
const data1 = [] , data2 = [] , data3 = [] ;
try {
const response = await unirest
.get('url')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.proxy("proxy")
const $ = cheerio.load(response.body)
$('hided').each((i,el) =>
{
data1[i] = $(el)
.find('hided')
.text()
data2[i] = $(el)
.find('hided')
})
$('hided').each((i,el) =>
{
data3[i] = $(el)
.find('hided')
.text()
})
if(data1.length && data2.length && data3.length))
{
return [data1 , data2 , data3]
}
}
catch(error)
{
console.log("Error" , error);
}
return [];
}
module.exports = getData
I am trying to get data from a function call and I am keeping it in a while loop so the function will be called again and again if data is not received. What I meant with the data is the data1,data2 and data3 arrays that I have returned from the getData function should be populated and not have a null value. But I am not able to find the solution.
Here is my code :
router.get('/someurl' , async(req,res) => {
let data = [];
while(data.length == 0)
{
data = await functionCall()
console.log(data)
}
})
And here is the format of my functionCall code :
const unirest = require("unirest");
const cheerio = require('cheerio')
const getData = async() => {
const data1 = [] , data2 = [] , data3 = [] ;
try {
const response = await unirest
.get('url')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.proxy("proxy")
const $ = cheerio.load(response.body)
$('hided').each((i,el) =>
{
data1[i] = $(el)
.find('hided')
.text()
data2[i] = $(el)
.find('hided')
})
$('hided').each((i,el) =>
{
data3[i] = $(el)
.find('hided')
.text()
})
if(data1.length && data2.length && data3.length))
{
return [data1 , data2 , data3]
}
}
catch(error)
{
console.log("Error" , error);
}
return [];
}
module.exports = getData
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先删除 if 语句,因为它实际上是 while 循环正在执行的操作。然后删除await,因为这不在异步函数中,并且它会出错。
Firstly remove the if statement, as it is literally what the while loop is doing. then remove await, as this is not in an async function, and it will make an error.
尝试这样的事情。
Try something like this.
假设
fetchData
是一个 API 调用,则没有理由最初定义data
。您可以只记录调用该 API 的结果,直到结果为空数组为止。Assuming that
fetchData
is an API call there's no reason to initially definedata
. You can just log the results of calling that API until the results are an empty array.