【问题标题】:How do I wait for axios get to be returned?我如何等待 axios 被退回?
【发布时间】: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


    【解决方案1】:

    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 并对其进行变异以获得结果)。

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 2018-02-15
      • 2018-09-19
      • 1970-01-01
      • 2011-09-20
      • 2019-07-08
      • 1970-01-01
      • 2019-12-09
      相关资源
      最近更新 更多