文章来自https://www.cnblogs.com/rogerwu/p/10784236.html
async 函数返回一个 Promise 实例对象,可以使用 then 方法添加回调函数。
当函数执行时,一旦遇到 await 就会先返回,等到异步操作完成,再接着执行函数体内后面的语句
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 函数内部 return语句返回的值,会成为then方法回调函数的参数
async function foo() { return 'hello world' }
foo().then(res => console.log(res)) // hello world
(2)、async 函数内部抛出错误,会导致返回的 Promise对象变成reject状态,抛出的错误会被catch方法回调函数接收到
async function bar() { return new Error('Error... ...')
}
bar().then(res => console.log(res))
.catch(err => console.log(err)) // Error: Error... ...
(3)、只有 async 函数内部的异步操作执行完,才会执行 then方法指定的回调函数
async function baz() {
await new Promise(resolve => {
console.log('执行第一个异步操作')
setTimeout(resolve, 2000)
})
await new Promise(resolve => {
console.log('执行第二个异步操作')
setTimeout(resolve, 3000)
}) return '异步执行完毕再执行then方法' }
baz().then(res => {console.log(res)})
实际应用
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
},