From 24aaadb743bbaf092df1b66272e7bad040226475 Mon Sep 17 00:00:00 2001 From: Bharath Kumar Date: Wed, 4 Dec 2019 13:06:22 +0000 Subject: [PATCH] Promise callback and async-await - reference --- callbacks.js | 28 +++++++++++++++++++ index.html | 22 +++++++++++++++ promises.js | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 callbacks.js create mode 100644 index.html create mode 100644 promises.js diff --git a/callbacks.js b/callbacks.js new file mode 100644 index 0000000..65a619e --- /dev/null +++ b/callbacks.js @@ -0,0 +1,28 @@ +const posts = [ + {title:'Post One', body: 'This is post one'}, + {title:'Post Two', body: 'This is post two'}, +]; + +function getPosts(){ + setTimeout(()=>{ + let output = ''; + posts.forEach((post, index)=>{ + + output += `
  • ${post.title}
  • `; + + }); + document.body.innerHTML = output; + + }, 1000) +} + + +function createPost(post, callback){ + + setTimeout(()=>{ + posts.push(post); + callback(); + }, 2000) +} + +createPost( {title:'Post Three', body: 'This is post three'}, getPosts); \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..233fdec --- /dev/null +++ b/index.html @@ -0,0 +1,22 @@ +! + + + + + + + + Async JS + + + + + + + + + + + \ No newline at end of file diff --git a/promises.js b/promises.js new file mode 100644 index 0000000..0d17241 --- /dev/null +++ b/promises.js @@ -0,0 +1,79 @@ +const posts = [ + {title:'Post One', body: 'This is post one'}, + {title:'Post Two', body: 'This is post two'}, +]; + +function getPosts(){ + setTimeout(()=>{ + let output = ''; + posts.forEach((post, index)=>{ + + output += `
  • ${post.title}
  • `; + + }); + document.body.innerHTML = output; + + }, 1000) +} + + +function createPost(post, callback){ + + return new Promise((resolve, reject)=>{ + + setTimeout(()=>{ + posts.push(post); + const error = false; + if(!error) + { + resolve(); + } + else + { + reject('Error something went wrong'); + } + }, 2000) + + }); + + +} + +async function init(){ + await createPost({title:'Post One', body: 'This is post one'}); + getPosts(); +} + +init(); + +// Aysnc/ Await and / fetch + + +async function fetchusers(){ + const res = await fetch('https://jsonplaceholder.typicode.com/users'); + const data = await res.json(); + console.log(data); + +} + +fetchusers(); + +/* +createPost( {title:'Post Three', body: 'This is post three'}).then(getPosts).catch((err)=>{ + console.log(err); +}); +*/ + + +/** promise all */ +const Promise1 = Promise.resolve('Hello World!'); +const Promise2 = 10; +const Promise3 = new Promise((resolve, reject)=>{ + setTimeout(resolve, 2000, 'Good Bye'); +}); +const Promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json()); + +Promise.all([Promise1, Promise2, Promise3, Promise4]).then((values)=>{ + + console.log(values); +}); \ No newline at end of file