- async 函数是什么?一句话,它就是 Generator 函数的语法糖。
- async 函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已。
- await 后面接一个会return new promise的函数并执行它
- await 只能放在async函数里
- await 命令只能出现在 async 函数内部,否则都会报错。
function ysz() {
return new Promise((resolve, reject) => {
let sino = parseInt(Math.random() * 6 + 1)
setTimeout(() => {
resolve(sino)
}, 3000)
})
}
async function test() {
let n = await ysz();
console.log(n); // 如果不用async和await,这块的log会先执行输出Promise { <pending> }
}
test();
function nn(){
return new Promise(resolve => {
setTimeout(function () {
resolve(22)
},1000)
})
}
async function fn() {
console.log(11)
await nn().then(value => console.log(value))
console.log(33)
}
fn() // 11 22 33
可参考博客:阮一峰 async 函数的含义和用法
网友评论