【发布时间】:2016-04-06 12:44:28
【问题描述】:
在调试器中测试的问题是,它将进入第一个函数(直到 $.get() 没有实际得到任何东西)然后跳到第二个函数(再次,直到 @987654322 @)。然后,它将继续执行第一个函数,直到完成检索所有项目,然后当它进入第二个函数时,它会做同样的事情,但出于某种神秘的原因,videoIdChainStr 将所有视频 id 保存在一个字符串中自从我怀疑以来,第一个函数从未被检索或执行过,它已经执行了第二个函数的 $.get(...) 并且当它具有值时再也没有“第二次”执行它。为了解决这个问题,我想到了异步操作,一开始有点困惑,但是在阅读了一些文章之后,我理解了一些,但不是 100%,尤其是还没有在代码中,但我尝试了以下代码:
我想真正了解在这种情况下如何使用 $.Deferred、resolve() 和 promise() 以及如果适用的话,还有其他方法,例如 then(),因为我只需要一个 resolve 和 promise 来返回一个填充的值 (videoIdChainStr) 到所需的 done() 并在其后执行第二个函数。
第一个功能:
var relatedVidsDefer = function relatedVids(videoId)
{
var videoIdChainStr = null;
var deferredVal = $.Deferred(); // instantiate defer object
$.get( // get related videos related to videoId
"https://www.googleapis.com/youtube/v3/search",
{
part: 'snippet',
maxResults: vidResults,
relatedToVideoId: videoId,
order: 'relevance',
type: 'video',
key: 'XXXXXXX'
},
function(data)
{
$.each(data.items,
function(i, item)
{
try
{
console.log(item);
var vidTitle = item.snippet.title; // video title
var vidThumbUrl = item.snippet.thumbnails.default.url;
var channelTitle = item.snippet.channelTitle;
var extractVideoId = null; // var to extract video id string from vidThumbUrl
// check if vidThumbUrl is not null, empty string, or undefined
if(vidThumbUrl)
{
var split = vidThumbUrl.split("/"); // split string when '/' seen
extractVideoId = split[4]; // retrieve the fourth index on the fourth '/'
}
else console.error("vidThumbUrl is either undefined or null or empty string.");
// if video title is longer than 25 characters, insert the three-dotted ellipse
if(vidTitle.length > 25)
{
var strNewVidTitle = vidTitle.substr(0, 25) + "...";
vidTitle = strNewVidTitle;
}
// check whether channelTitle is the same
if(channelTitle === "Channel Name")
{
extractedVideoIdArr.push(extractVideoId); // add the extracted video id to the array
// check if extractedVideoIdArr is not empty
if(extractedVideoIdArr !== 'undefined' && extractedVideoIdArr.length > 0)
{
videoIdChainStr = extractedVideoIdArr.join(", "); // change from an array to a chain string of videoIds for the relatedVidsDetails()
}
deferredVal.resolve(videoIdChainStr); // get the value
var vidThumbnail = '<div class="video-thumbnail"><a class="thumb-link" href="single-video.html"><div class="video-overlay"><img src="imgs/video-play-button.png"/></div><img src="' + vidThumbUrl + '" alt="No Image Available." style="width:204px;height:128px"/></a><p><a class="thumb-link" href="single-video.html">' + vidTitle + '</a><br/></div>';
// print results
$('.thumb-related').append(vidThumbnail);
$(item).show(); // show current video thumbnail item
}
else $(item).hide(); // hide current video thumbnail item
}
catch(err)
{
console.error(err.message); // log error but continue operation
}
}
);
}
);
return deferredVal.promise(); // return the value and execute the second function
};
第二个功能:
var relatedVidsDetailsDefer = function relatedVidsDetails(videoIdChainStr)
{
// change extractvideoid into a string by tostring() or join() for param to recognize
console.log("initial: ", extractedVideoIdArr);
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'snippet, contentDetails, statistics',
id: videoIdChainStr, // chain string of video ids to be called upon in a single request
key: 'XXXXXXX',
},
function(data)
{
$.each(data.items,
function(i, item)
{
try
{
var _vidDuration = item.contentDetails.duration;
var _viewCount = item.statistics.viewCount;
console.log("id: " + extractedVideoIdArr[i] + " duration: " + _vidDuration);
console.log("id: " + extractedVideoIdArr[i] + " viewCount: " + _viewCount);
$('.vidDetails').append(convert_time(_vidDuration) + ' / Views: ' + _viewCount);
}
catch(err)
{
console.error(err.message); // log error but continue operation
}
}
);
}
);
};
执行:
relatedVidsDefer(_videoId).done(relatedVidsDetailsDefer); // wait till first function (before .done parameter) is complete before executing the second (in .done paramater)
更新:
使用@valarauko 的答案更新代码。最后,它起作用了,并且能够检索复制到其余视频的其中一个视频的视频详细信息。进入第二个函数后,videoIdChainStr 只有第一个 id 而没有其余的...字符串的其余部分,即使它继续循环并解析所有项目。
例如:
假设将ID1, ID2, ID3 传递给参数,但只传递ID1。因此,为什么它只通过第二个函数的每个循环一次。如何解决此问题?
【问题讨论】:
标签: javascript jquery youtube-api promise jquery-deferred