我正在使用 YouTube API 密鑰來獲取搜索資料。
const key = "[API Key]";
const url = "https://www.googleapis.com/youtube/v3/search";
$(document).ready(function () {
const options = {
part: ["snippet"],
key: key,
maxResults: 10,
q: "developers",
};
loadVids();
function loadVids() {
$.getJSON(url, options, function (data) {
const videos = data.items;
console.log(videos);
});
}
});
它作業正常,但我想使用 vanilla javascript 將 $.getJSON() 轉換為異步等待。請指導我如何做到這一點。
uj5u.com熱心網友回復:
您可以通過定義一個 Promise 函式來實作,例如:
function loadVids(){
return new Promise((resolve, reject)=>{
fetch('https://www.googleapis.com/youtube/v3/search', {method: 'GET', body: options})
.then(response => response.json())
.then(data => {
console.log(data));
resolve();
})
.cache(err => reject());
});
}
然后等待它:
async function f1() {
var x = await loadVids();
//other code...
}
uj5u.com熱心網友回復:
我找到了一個解決方案不需要部分:['snippet']。它在不使用它的情況下正常作業。
const key = "[API Key]";
const url = "https://www.googleapis.com/youtube/v3/search";
const options = {
part: ["snippet"],
key: key,
maxResults: 10,
q: "developers",
};
async function loadVids() {
const res = await fetch(
`${url}?maxResults=${options.maxResults}&q=${options.q}&key=${options.key}`
);
//can also write the above line in this more sensible way
//const res = await fetch(
// `https://youtube.googleapis.com/youtube/v3/search?maxResults=${options.maxResults}&q=${options.q}&key=${options.key}`,
// );
const data = await res.json();
console.log(data);
}
loadVids();
更易懂的代碼
const apiKey = "[API Key]";
const url = "https://www.googleapis.com/youtube/v3/search";
const options = {
key: apiKey,
maxResults: 10,
q: "developers",
};
const { key, q, maxResults } = options;
async function loadVids() {
const res = await fetch(`${url}?maxResults=${maxResults}&q=${q}&key=${key}`);
const data = await res.json();
console.log(data);
}
loadVids();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314699.html
標籤:javascript 查询 阿贾克斯 异步等待 youtube-data-api
下一篇:根據回應的國家設定不同的價格
