Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Top to bottom (code read)
- //Instant (synchronous)
- //Not Instant (asynchronous)
- // API call
- // setTimeOut (our own)
- //file reading/file write , database data store, data fetch
- //asynchronous code dealing
- //callback
- //promise
- //Async await
- // function getOne() {
- // return 1
- // }
- // function getTwo() {
- // return 2
- // }
- // function getThree(callback) {
- // setTimeout(() => {
- // callback(3)
- // }, 2000)
- // }
- // function getFour(number) {
- // return number
- // }
- // console.log(getOne())
- // console.log(getTwo())
- // getThree(function (data) {
- // console.log(data) //result is available
- // //getFour()
- // // console.log(getFour(data + 1)) //Dependency
- // })
- // console.log(getFour())
- //promise pattern
- function getOne() {
- return 1
- }
- function getTwo() {
- return 2
- }
- function getThree(isResolved) {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- if (isResolved) {
- resolve(3)
- } else {
- reject(new Error(3))
- }
- }, 2000)
- })
- }
- function getFour(number) {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- resolve(number)
- }, 2000)
- })
- }
- console.log(getOne())
- console.log(getTwo())
- // console.log(getThree())
- getThree(true)
- .then(data => {
- console.log(data)
- return getFour(data + 1)
- // .then(fourData => console.log(fourData))
- // .catch(err => console.log(err))
- // console.log(getFour(data + 1))
- })
- .then(data => console.log(data))
- .catch(err => console.log(err))
- // console.log(getFour(4))
- //callback hell(nesting callback)
- //Async await uses promise (Behind the scene)
- //fetch
- // fetch('https://jsonplaceholder.typicode.com/todos')
- // .then(res => res.json())
- // .then(data => console.log(data))
- // .catch(err => console.log(err))
- async function init() {
- try {
- const todos = await (
- await fetch('https://jsonplaceholder.typicode.com/todos')
- ).json()
- // const todos = await res.json()
- return todos
- } catch (err) {
- console.log(err)
- }
- }
- ;(async function () {
- console.log(await init())
- })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement