Home > Mobile >  Convert jquery .getJSON to ajax async await for YouTube API
Convert jquery .getJSON to ajax async await for YouTube API

Time:10-14

I am using YouTube API key to fetch data on search.

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

It is working properly but I want to convert $.getJSON() to async await using vanilla javascript. Please guide me how to do this.

CodePudding user response:

You can do it by defining a Promise function like:

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

and then await on it:

async function f1() {
   var x = await loadVids();
   //other code...
}

CodePudding user response:

I found a solution There is no need of part: ['snippet']. It is working properly without using that.

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

More understandable code

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