【问题标题】:Convert jquery .getJSON to ajax async await for YouTube API将 jquery .getJSON 转换为 ajax 异步等待 YouTube API
【发布时间】:2021-12-02 00:29:51
【问题描述】:

我正在使用 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() 转换为异步等待。请指导我如何做到这一点。

【问题讨论】:

标签: javascript jquery ajax async-await youtube-data-api


【解决方案1】:

你可以通过定义一个 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...
}

【讨论】:

  • 它返回错误:TypeError:无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文。
  • 错误很明显,但是您必须根据后端设置内容类型并区分您的数据。看看这个:stackoverflow.com/a/29823632/4437464
  • 谢谢。很有用
【解决方案2】:

我找到了解决方案 不需要部分:['sn-p']。不使用它也能正常工作。

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2021-01-22
    • 1970-01-01
    • 2021-05-17
    • 2015-12-13
    • 2012-05-04
    相关资源
    最近更新 更多