【发布时间】:2020-02-13 20:51:49
【问题描述】:
当我在 get() 中的 finally 块中 console.log 数组时,并非所有假设由 helper() 检索的值都不存在。我想这是因为 axios 方法是异步的。我认为如果我在 helper() 上使用 await 关键字,它将等待该方法,以便可以打印我想要的所有值,但这不会发生。有没有办法让我等待辅助方法?
(function get() {
let videoThumbnails = new Array();
axios.get(urlConstants.latestAnimeUrl)
.then((res) => {
if (res.status === 200) {
const html = res.data;
const $ = cheerio.load(html);
const thumbnails = $(".post div a img");
for (let i = 0; i < thumbnails.length; i++) {
let videoThumbnail = new Object;
videoThumbnail.thumbnailLink = thumbnails[i].attribs['data-cfsrc']; //image thumbnail link, thumbnail dimensions if needed
videoThumbnails.push(videoThumbnail);
}
const links = $("a[itemprop=url]")
links.each(async function (i, elem) {
if (i < thumbnails.length) {
videoThumbnails[i].thumbnailTitle = $(this).attr("title");
await helper($(this).attr("href").toString(),videoThumbnails,i);// link to video webpage, but need actual video link
}
});
}
})
.finally(() => {
console.log(videoThumbnails);
});
return videoThumbnails;
})();
function helper(chiaUrl,videoThumbnails,index) {
axios.get(chiaUrl)
.then((response) => {
if (response.status == 200) {
const $ = cheerio.load(response.data);
const videoLink = $("div[id=load_anime] div iframe");
videoThumbnails[index].thumbnailLink = videoLink.attr("src");
}
})
.finally(()=> {
})
}
【问题讨论】:
标签: javascript html async-await axios