Javascript: async await fetch Api [get and post ]
// async function getdata() {
// return new Promise((resolve, reject) => {
// setInterval(() => {
// resolve(455);
// }, 40000);
// });
// }
async function getdata() {
let x = await fetch("https://jsonplaceholder.typicode.com/todos/1");
data = await x.json();
console.log(data);
return 455;
// .then((response) => response.json())
// .then((json) => console.log(json));
}
async function postreqexample() {
let x = fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
}
async function main() {
console.log("Running code");
console.log("Fetching data ");
// await wait krna h promise k resolve ya rejject hone ka wait
let data = await postreqexample();
console.log(data);
console.log("Processing data ");
}
main();
// async function main() {
// console.log("Running code");
// console.log("Fetching data ");
// // await wait krna h promise k resolve ya rejject hone ka wait
// let data = await getdata();
// console.log(data);
// console.log("Processing data ");
// }
// main();
// console.log("Running code");
// console.log("Fetching data ");
// let data = getdata();
// console.log(data);
// console.log("Processing data ");
// let data = getdata();
// data.then ((v) => { console.log(data);
// console.log(data);
// console.log("Processing data ");
// })
Comments
Post a Comment