当我在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(()=> {
})
}
答案 0 :(得分:0)
axios.get
返回一个承诺。诺言可以被束缚和等待。
您的helper
函数返回undefined
。您应该返回axios.get
function helper(chiaUrl,videoThumbnails,index) {
return 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(()=> {
})
}
还值得注意的是,如果您在.then
内返回内容,那将是等待的结果(这样您就不必传递videoThumbnails
并对其进行变异即可获得结果)。