Async - Await Practice

New JS Async and Await

by Allie Yu

JavaScript

class Animal{ 

	constructor(name,type){
  		this.animal = true; 
  		this.name = name
      this.type= type 
  }
	sayHello(){
   //console.log('heyyyaaa')
   var num = Math.random() * 10; 
   return new Promise( (resolve,reject) => {
    	/*(num >= 5)? resolve('Yesss ' + num) : reject('Failed ' + num )
      */
      setTimeout( () => resolve('Babbbyy i need your loving') , 4000 )
   })
  }
  async asyncHello(){
  	const greeting = await this.sayHello()
    console.log(greeting)
    console.log('Im only gonna run after sayhello is finished , after promise is reolved')
  }
 
}


let leto = new Animal('leto', 'lion')

//console.log(leto)
//leto.asyncHello()

// Whole block is executed only after the this.sayHello() function finishes . Everything after await doesnt happen until the aysnchronous call completes 


// Example 2: 

const sampleFetch  = () => { 
		return new Promise( (resolve, reject) => { 
    			// reject('Opps something went wrong')
        	resolve( JSON.stringify({text: 'oooppsss i did it again'}))
    })
}

const sampleFetchTwo = () => {
	return new Promise( (resolve,reject) => {
  		let num = Math.random() * 10; 
      if(num >= 5){ 
      			return resolve(JSON.stringify({message: 'success' , data: num}))
        }else {
        	return reject( JSON.stringify({ message: 'Failed' , data: num }))
        }
  })
}

const foo = ( ) => {
 		return sampleFetch()
    	.then(data => console.log( JSON.parse(data , 'version 1')))
      .catch( err => console.error(err) )
}

const fooTwo = async () => { 
		let ans = await sampleFetch()
  	let ans2 = await sampleFetch();
    let ans3 = await sampleFetch();
    
    console.log([ans ,ans2 , ans3 ])
  } 

const fooThree = async () => {
 	try{ 
  	let res = await sampleFetchTwo();
    console.log( JSON.parse(res))
    console.log('In an application , we would run some more methods here')
  }
  catch(err){
   console.log('Error occurred',err)
   console.log('In a real world app, we would do some cool stuff here...