I have a project where I am parsing a fast-food menu using Request-Promise and Cheerio, then returning an "order" based on what a user asks for. However, I am having some trouble outputting the "order" which I am storing as an array.
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)
Currently, the output is:
[]
[
'drink1',
'drink2',
'drink3'
]
If I change the code to the following:
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)
The log is
2
1
So I know my problem is the the "order" array isn't filled when I try and output it because it is being logged first, my question is how can I await the array being filled, then output it?
Your
getItemfunction should return aPromiseand then you can either use thePromise.prototype.then()method on it or theawaitkeyword to make sure you wait for the results before trying to process them.Here's a simple example with some fake
rpfunction and data:Alternative with
async/await: