DEV Community

Cover image for Fetch to var
Abhigyan
Abhigyan

Posted on

Fetch to var

In this huge world of JSON APIs, fetch is the most common implementation for receiving an HTTP response from an API. However, it's a lot more difficult for newbies to get the fetch data into a variable. Here it is:

This code block is no longer available. The original code is shown below.


    
const fetch = require("node-fetch")

  

    
// A function to get data from a URL
async function getData(url) {
    const x = await fetch(url)  // We wait for the data to arrive
    return await x.json()  // We wait for the data to convert to JSON
}

// We wait for the data to arrive
const data = await getData("https://jsonplaceholder.typicode.com/todos/1")

// We log/print the arrived JSON data
console.log(data)

  

Top comments (0)