调用async function 返回一个 promise
await一定要在有async的函数的作用域里面使用
await 基于 promise 函数
await会停在当前行代码,等到promise完成并返回结果值
await使得异步操作更像是同步代码
async和await的使用减少了.then()的调用
添加错误处理
可以使用 try catch 语句
也可以使用.then()后面接.catch()
promise和async、await的配合使用:代码示例
function gamble(bet){return new Promise((resolve,reject)=>{setTimeout(()=>{let n = Math.floor(Math.random()*6)+1;if(n>3){if(bet==='大'){resolve(n)}else{reject(n)}}else{if(bet==='大'){reject(n)}else{resolve(n)}}},1000);});}// gamble('大').then(// value=>{// console.log('你赢了')// console.log(value);},// reason=>{// console.log('你输了');// console.log(reason);// })async function test(){try{let n = await gamble('大')console.log(n)console.log('赚大了')}catch(error){console.log(error)console.log('输惨了')}}test()
Promise和Promise.all和async、await配合使用:代码示例
function gamble(bet) {return new Promise((resolve, reject) => {setTimeout(() => {let n = Math.floor(Math.random() * 6) + 1;if (n > 3) {if (bet === "大") {resolve(n);} else {reject(n);}} else {if (bet === "大") {reject(n);} else {resolve(n);}}}, 1000);});}let resultObj = Promise.all([gamble("大"), gamble("大")]);console.log(resultObj);// resultObj.then(// value=>{// console.log('你赢了')// console.log(value);},// reason=>{// console.log('你输了');// console.log(reason);// }// )async function test() {try {let n = await resultObj;console.log(n);console.log("血赚");} catch (error) {console.log(error);console.log("血亏");}}test();
