skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search