Promise/Gennerator/async&await解决
2021-09-10 本文已影响0人
东方三篇
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>Document</title>
</head>
<body>
<div id='dog' style="width: 400px; height: 400px; background-size: 100%;"></div>
<script>
const box = document.getElementById('dog')
const url = 'https://dog.ceo/api/breeds/image/random' // 获取狗狗图片的开放api
const {log} = window.console
/* 定义一个常规的 ajax promise */
const Get = () => {
return new Promise((resolve, reject) => {
const data = axios.get(url) // ajax获取狗狗图片
data ? resolve(data) : reject(new Error('获取失败!'))
})
}
/* promise then方法来获取 ajax 的response */
/* Get().then(res => {
log(res)
box.style.backgroundImage = `url(${res.data.message})`
}).catch(err => log(err)) */
/* 使用 Generator 函数解决 ajax */
/* const Gen = function * () {
const res = yield axios.get(url) // axios返回的是promise所以可以是用then方法
return res
} */
/* const Gen = function * () {
const res = yield Get() // 返回值p是promise所以可以then
return res
} */
/* const hw = Gen()
const result = hw.next()
console.log('result', result) // result {value: Promise, done: false}
result.value.then(res => { // axios返回的是promise所以可以是用then方法
console.log('res', res)
box.style.backgroundImage = `url(${res.data.message})`
}).catch(err => log(err)) */
/* 使用 async await 解决 ajax */
const AsyncGet = async () => {
const res = await Get() // Get 返回 promise
log('res', res) // await 执行 完成,才执行下面一行
box.style.backgroundImage = `url(${res.data.message})`
}
AsyncGet()
console.log('end')
</script>
</body>
</html>