结论说前
推荐使用async和await,语法看起来更简洁和顺眼
区别
pormise的then 和catch不会阻塞后面的代码
console.log('.then代码的之前');
api()
.then((e) => {
console.log('.then执行了');
})
console.log('.then代码的之前');
而 await/async 并不会阻塞后面,而且比promise读起来更顺
async function test() {
console.log('.await代码的之前');
data = await api()
console.log('.await代码的之后');
}
一些坑
1 使用pormise时候,用回调拿返回值,而不是return,这个最容易犯错
错误的使用return拿返回值
function getData(success) {
let res=null
api()
.then((e) => {
res=e
})
return res
}
let res= getData()
setTimeout(()=>{
console.log(res);
},2000)
应该使用回调函数
function getData(success) {
let res=null
api()
.then((e) => {
success(e)
})
}
let res=null
getData((e)=>{res=e})
setTimeout(()=>{
console.log(res);
},2000)
**2 只要被async声明了,那么这个函数的返回值就自动变成了Promise,意思就是这个函数可能过一会才会有值,函数内return的值会被自动resolve,thorw和任何错误会被自动reject **
async function test() {
return 1
}
test()
.then((e) => {
console.log('e', e); //e 1
})
.catch((e) => {
console.log('error', e);
})
async function test() {
throw '出错啦'
}
test()
.then((e) => {
console.log('e', e);
})
.catch((e) => {
console.log('error', e);
})