【发布时间】:2020-12-09 18:58:04
【问题描述】:
我有一个项目,我正在使用 Request-Promise 和 Cheerio 解析快餐菜单,然后根据用户的要求返回“订单”。但是,我在输出存储为数组的“订单”时遇到了一些问题。
var rp = require('request-promise');
var cheerio = require('cheerio');
var tempMenu = [];
var order = [];
function getItem(item) {
var itemUrl = baseURL + '/' + item
var itemMenu = {
uri: itemUrl,
transform: function (body) {
return cheerio.load(body);
}
};
rp(itemMenu)
.then(function ($) {
//.class #id tag
$(".product-card .product-name a").each(function () {
tempMenu.push($(this).text());
order.push(tempMenu[Math.floor(Math.random() * tempMenu.length)]);
});
console.log(order)
})
.catch(function (err) {
});
}
getItem('drinks')
console.log(order)
目前,输出为:
[]
[
'drink1',
'drink2',
'drink3'
]
如果我将代码更改为以下内容:
rp(itemMenu)
.then(function ($) {
//.class #id tag
$(".product-card .product-name a").each(function () {
tempMenu.push($(this).text());
order.push(tempMenu[Math.floor(Math.random() * tempMenu.length)]);
});
console.log(1)
})
.catch(function (err) {
});
}
getItem('drinks')
console.log(2)
日志是
2
1
所以我知道我的问题是当我尝试输出“订单”数组时它没有被填充,因为它是首先被记录的,我的问题是我如何等待数组被填充,然后输出它?
【问题讨论】:
-
您几乎在 我如何等待数组被填充 处回答您自己的问题;使用
async / await。 -
@EmielZuurbier 你是对的 - 我想我只需要输入它。将我的函数更改为异步函数,并将 await 添加到我的 rp() 和 getItems() 中对其进行了整理。谢谢!
标签: javascript jquery cheerio request-promise