async 函数是返回的 Promise 对象
虽然async 跟await 跟 Promise 一样都是解决异步的,但是async跟await 不需要写. then 也不需要写回调函数,代码相对来说更加的简洁,也减少了很多代码之间的嵌套
async跟await 最大的价值,还是在异步的时候在形式上更接近于同步的写法,代码的可读性更加的强,可维护性更加的强
async function foo(){
return 'xx'
}
console.log(foo()) // Promise {<resolved>: 'xx'}
Promise.resolved('xx')
async function foo(){
let result = await 'xx'
console.log(result)
}
foo()
function timeout() {
return new Promise(resolve => {
setTimeout(()=>{
cosnole.log(1)
resolve()
},1000)
})
}
async function foo(){
await timeout() // 加了await 之后会等待异步执行完之后才会执行下面的代码
console.log(2)
}
foo()
foo.then(res => {
cosnole.log(res);
}).catch(err => {
console.log(err)
})
// 简单的数据请求代码
async function request(){
conat data = await axios.get('http://www.xx.com')
console.log(data)
}
// 实例代码
function request(url) {
return new Promise(resolve => {
ajax(url, res => {
resolve(res)
})
})
}
async function getData(){
const res1 = await requect('static/a.json')
console.log(res1)
const res2 = await requect('static/b.json')
console.log(res2)
const res3 = await requect('static/c.json')
console.log(res3)
}
getData()
- async 需要写在function的前面
- async跟await 需要成对出现的
- await 必须写在 async 的里面
- 虽然async 跟await 跟 Promise 一样都是解决异步的,但是async跟await 不需要写. then 也不需要写回调函数,代码相对来说更加的简洁,也减少了很多代码之间的嵌套
- async跟await 最大的价值,还是在异步的时候在形式上更接近于同步的写法,代码的可读性更加的强,可维护性更加的强