小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
关于Promise你必须知道几件事
针对异步编程,我们看下Ajax的回调形式:
// 回调形式调用
$.ajax({
url,
data,
success:function(result){
$.ajax({
data:result,
success: function(result1){
$.ajax({
url,
data: result1
})
}
})
}
})
promise的链式回调函数
为了解决一层层的嵌套,使代码更加优雅:
// 链式调用 没有嵌套
axios({ url, data}).then(result => {
return axios({ data:result })
}).then(result1 => {
return axios({ data:result1 })
}).then(result2 => {
return axios({ data: result2 })
}).then(result3 => {
return axios({ data: result3 })
})
如何声明一个Promise
new Promise(function(resolve, reject){ })
如果想让Promise成功执行下去,需要执行resolve,如果让它失败执行下去,需要执行reject
new Promise(function(resolve, reject) {
resolve('success') // 成功执行
}).then(result => {
alert(result)
})
new Promise(function(resolve, reject) {
reject('fail') // 成功执行
}).then(result => {
alert(result)
}).catch(error => {
alert(error)
})
如果想终止在某个执行链的位置,可以用Promise.reject(new Error())
new Promise(function(resolve, reject) {
resolve(1)
}).then(result => {
return result + 1
}).then(result => {
return result + 1
}).then(result => {
return Promise.reject(new Error(result + '失败'))
// return result + 1
}).then(result => {
return result + 1
}).catch(error => {
alert(error)
})
异步编程的终极方案 async /await
async 和 await实际上就是让我们像写同步代码那样去完成异步操作
async test () {
// await总是会等到 后面的promise执行完resolve
// async /await就是让我们 用同步的方法去写异步
const result = await new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(5)
}, 5000)
})
alert(result)
}
上面代码会等待5秒之后,弹出5
async 和 await必须成对出现 由于await的强制等待,所以必须要求使用await的函数必须使用async标记, async表示该函数就是一个异步函数,不会阻塞其他执行逻辑的执行
async test () {
const result = await new Promise(function(resolve){
setTimeout(function(){
resolve(5)
},5000)
})
alert(result)
},
test1(){
this.test()
alert(1)
}
通过上面的代码我们会发现,异步代码总是最后执行,标记了async的函数并不会阻塞整个的执行往下走 如果你想让1在5弹出之后再弹出,我们可以这样改造
async test1(){
await this.test()
alert(1)
}
// 这充分说明 被async标记的函数返回的实际上也是promise对象
如果promise异常了怎么处理?
promise可以通过catch捕获,async/ await捕获异常要通过 try/catch
async getCatch () {
try {
await new Promise(function (resolve, reject) {
reject(new Error('fail'))
})
alert(123)
} catch (error) {
alert(error)
}
}
async / await 用同步的方式 去写异步~~~