如下所示,我将对象link_to_json
返回到html_to_json
中声明的数组allShirts
中。Node.js - 如何在所有异步调用完成后返回
但是,第三行的console.dir
和返回值html_to_json
记录了一个未定义引用的数组。我认为这是因为console.dir
和return
在link_to_json
函数完成之前执行。
我该如何确保html_to_json
的返回值是填充allShirts
数组?
//Go to individual links and scrape relevant info
const link_to_json = (link) => {
request(link, (err, res, body) => {
if (!error_handler(err, res, link)) {
const $ = cheerio.load(body);
const shirt_detail = $('.shirt-details').find('h1').text();
const Title = shirt_detail.substr(shirt_detail.indexOf(' ') + 1);
const Price = shirt_detail.substr(0, shirt_detail.indexOf(' '));
const ImageURL = $('.shirt-picture').find('img').attr('src');
const URL = link;
return new Shirt(Title, Price, ImageURL, URL);
} else return {};
});
}
//Crawl through all individual links listed in Root
const html_to_json = body => {
const allShirts = [];
const $ = cheerio.load(body);
$('.products').find('a').each((index, val) => {
allShirts.push(link_to_json(rootURL + $(val).attr('href')));
});
console.dir(allShirts); // <--- HERE
return allShirts;
}
是请求异步方法?我会说使用诺言。 – Apidcloud
我不认为'Promise.all()'防止'html_to_json'返回,它确保'html_to_json'返回一切或没有。 –
是的,但你可以使用。然后 – Apidcloud