【问题标题】:How do I get actual returned value from a chain of promises?如何从一系列承诺中获取实际返回值?
【发布时间】:2019-05-12 00:09:22
【问题描述】:

我正在尝试使用一个函数来获取使用 YouTube API 的视频的观看次数。虽然我可以通过控制台日志查看查看次数,但我在 HTML 页面上得到了“未定义”

我尝试了 .toString() 方法,但无济于事

let views = document.createElement('p');
views.innerHTML = '<i class="fas fa-eye"></i>' + getViews(video);

...

const getViews = (video) => {
    const url = 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=' + video.id + '&key=' + api;
    // console.log(url);
    fetch(url).then((response) => {
        return response.json();
    }).then((data) => {
        console.log(data.items[0].statistics.viewCount); // it works here
        return data.items[0].statistics.viewCount; // but not here 
    }).catch((error) => {
        console.log(error);
    })
};

我希望 getViews 函数返回一个字符串,其中包含作为函数参数传递的视频的观看次数

【问题讨论】:

    标签: javascript html ecmascript-6 youtube-api


    【解决方案1】:

    returnfetch:

    return fetch(url).then(...).then(...).catch(...);
    

    【讨论】:

    • 然后我的页面上出现 [object Promise]
    • 我的错 - 当您将其添加到页面时,请执行以下操作:getViews(video).then(r =&gt; r)。这行得通吗?
    • views.innerHTML = '' + getViews(video).then(r => r);不,我仍然得到 [object Promise] 渲染
    • return fetch 很重要,但是你如何使用它更重要 - 检查这个 pastebin pastebin.com/xAbzpWPL @ВебКирпичи
    • .then(r =&gt; r) 本质上是一个 NOP :p
    【解决方案2】:
    views.innerHTML = '<i class="fas fa-eye"></i>' + getViews(video);
    

    getViews不可能同步返回http调用的结果,因为结果还不存在。您需要更改 getViews 以返回一个 Promise,然后您可以使用它的 .then 方法获得该 Promise 的结果:

    const getViews = (video) => {
        const url = 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=' + video.id + '&key=' + api;
        return fetch(url).then((response) => { // <--- added return
            return response.json();
        }).then((data) => {
            console.log(data.items[0].statistics.viewCount);
            return data.items[0].statistics.viewCount;
        }).catch((error) => {
            console.log(error);
        })
    };
    
    getViews(video)
      .then(viewCount => {
        // Moved the code into the .then
        let views = document.createElement('p');
        views.innerHTML = '<i class="fas fa-eye"></i>' + viewCount;
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-02
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多