文章來自https://www.cnblogs.com/rogerwu/p/10784236.html
async 函數(shù)返回一個(gè) Promise 實(shí)例對(duì)象瓣赂,可以使用 then 方法添加回調(diào)函數(shù)痊硕。
當(dāng)函數(shù)執(zhí)行時(shí),一旦遇到 await 就會(huì)先返回植酥,等到異步操作完成,再接著執(zhí)行函數(shù)體內(nèi)后面的語句
function sleep(ms) { return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
async function print(ms) {
console.log('start... ...')
await sleep(ms)
console.log('end... ...')
}
print(1000)
(1)鹃栽、async 函數(shù)內(nèi)部 return語句返回的值布蔗,會(huì)成為then方法回調(diào)函數(shù)的參數(shù)
async function foo() { return 'hello world' }
foo().then(res => console.log(res)) // hello world
(2)、async 函數(shù)內(nèi)部拋出錯(cuò)誤拯刁,會(huì)導(dǎo)致返回的 Promise對(duì)象變成reject狀態(tài)脊岳,拋出的錯(cuò)誤會(huì)被catch方法回調(diào)函數(shù)接收到
async function bar() { return new Error('Error... ...')
}
bar().then(res => console.log(res))
.catch(err => console.log(err)) // Error: Error... ...
(3)、只有 async 函數(shù)內(nèi)部的異步操作執(zhí)行完垛玻,才會(huì)執(zhí)行 then方法指定的回調(diào)函數(shù)
async function baz() {
await new Promise(resolve => {
console.log('執(zhí)行第一個(gè)異步操作')
setTimeout(resolve, 2000)
})
await new Promise(resolve => {
console.log('執(zhí)行第二個(gè)異步操作')
setTimeout(resolve, 3000)
}) return '異步執(zhí)行完畢再執(zhí)行then方法' }
baz().then(res => {console.log(res)})
實(shí)際應(yīng)用
getDetail(id){
return new Promise(resolve => {
let _this = this;
let param = {
goodsId:id,
}
api.getVideoDetails(param,function(success,data,err){
if(success) {
if(data.status == 200) {
_this.detail = data.body
}
}
resolve()
})
})
},
toCourseDetail: async function(id){
let _this = this;
await _this.getDetail(id)
console.log('jfksjklfj'+_this.detail.course)
// 接口返回值后割捅,再使用this.detail
},