“JS Cara Mengambil Data” Kode Jawaban

Ambil data dari URL API

fetch('https://jsonplaceholder.typicode.com/posts').then(function (response) {
	// The API call was successful!
	return response.json();
}).then(function (data) {
	// This is the JSON from our response
	console.log(data);
}).catch(function (err) {
	// There was an error
	console.warn('Something went wrong.', err);
});
Joynal Abedin

JS Cara Mengambil Data

// way 1
const getData = async (url) => {
  const response = await fetch(url)
  const json = await response.json()

  return json
}

const url = `https://jsonplaceholder.typicode.com/posts?userId=3`

try {
  const data = await getData(url)
  console.log(data)
} catch (error) {
  console.log(error.message)
}

/* ------------ Way 2 --------------- */
const getData = (url) =>
  new Promise((resolve, reject) => {
    fetch(url)
      .then(response => response.json())
      .then(json => resolve(json))
      .catch(error => reject(error))
  })

const url = `https://jsonplaceholder.typicode.com/todos?completed=true&userId=2`

getData(url)
  .then(data => console.log(data))
  .catch(error => console.log(error.message))
Condemned Corncrake

Jawaban yang mirip dengan “JS Cara Mengambil Data”

Pertanyaan yang mirip dengan “JS Cara Mengambil Data”

Lebih banyak jawaban terkait untuk “JS Cara Mengambil Data” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya