What is the reason for async/await?

Promise’s programming model was still riddled with then methods, and while it solved the problem of callback hell, it was still semantically flawed, with a lot of THEN functions in the code.

What are the benefits of using async/await? How do you do that?

Using async/await allows asynchronous code to be written in a synchronous code style that not only makes the code look cleaner, but also ensures that the function always returns promises. This is because the underlying technology of async/await uses generators and promises. Generators are implementations of coroutines with which generator functions can be paused and resumed. In addition, the V8 engine does a lot of syntactic wrapping for async/await.

Fetch

fetch('https://www.geekbang.org')
.then((response) => {          
	console.log(response)          
	return fetch('https://www.geekbang.org/test')      
}).then((response) => {          
	console.log(response)      
}).catch((error) => {          
	console.log(error)      
})


Copy the code

async/await

async function foo(){  
	try{    
		let response1 = await fetch('https://www.geekbang.org')    				console.log('response1')    
		console.log(response1)    
		let response2 = await fetch('https://www.geekbang.org/test')    		console.log('response2')    
		console.log(response2)  
	} catch(err) {      
    	console.error(err)  
    }
}
foo()

Copy the code

Generator function

Function * genDemo() {console.log(" start executing first paragraph ") yield 'generator 2' console.log(" start executing second paragraph ") yield 'generator 2' Console. log(" start execution third paragraph ") yield 'generator 2' console.log(" finish execution ") return 'generator 2'} console.log('main 0') let gen = genDemo() console.log(gen.next().value) console.log('main 1') console.log(gen.next().value) console.log('main 2') console.log(gen.next().value) console.log('main 3') console.log(gen.next().value) console.log('main 4')Copy the code

Generator + Promise

function* foo() { let response1 = yield fetch('https://www.geekbang.org') console.log('response1') console.log(response1) let response2 = yield fetch('https://www.geekbang.org/test') console.log('response2') Console. log(response2)} let gen = foo() function getGenPromise(gen) {return gen.next().value} getGenPromise(gen).then((response) => console.log('response1') console.log(response) return getGenPromise(gen) }).then((response) => { console.log('response2') console.log(response) })Copy the code

actuator

function* foo() {    
	let response1 = yield fetch('https://www.geekbang.org')    	  		 	 console.log('response1')    
	console.log(response1)    
	let response2 = yield fetch('https://www.geekbang.org/test')    	 	 console.log('response2')    
	console.log(response2)
}
co(foo())

Copy the code