我正在嘗試從函式呼叫中獲取資料,并將其保存在 while 回圈中,因此如果未收到資料,將一次又一次地呼叫該函式。當我從 getData() 控制臺資料時,它成功顯示了回應,但是為什么我沒有從函式呼叫中接收到資料,return 陳述句有什么問題嗎?. 請更正我的代碼。
這是我的代碼:
router.get('/someurl' , async(req,res) => {
let data = [];
while(data.length == 0)
{
data = await getData()
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
uj5u.com熱心網友回復:
首先,不要這樣做 while 回圈。您只需要等待函式呼叫。
問題是您沒有解決以 unirest 呼叫開始的 Promise。在快速的谷歌搜索中,我發現缺少的是一個 .exec() 呼叫,它將回傳可以等待的正確 Promise。所以:
const response = await unirest
.get('url')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.proxy("proxy")
.exec(); //here will make request awaitable
請記住洗掉將使 nodejs 事件回圈阻塞的 while 回圈。
uj5u.com熱心網友回復:
我剛發現代碼沒有問題,不知道為什么之前嘗試沒有回傳,但現在成功回傳資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451983.html
標籤:javascript 节点.js 表示
