开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详情
前言
今天先回头来学习JavaScript的异步相关知识~
ES6新特性Promise对象
基本使用
在ES6标准中引入了Promise对象,用于提供一种更优雅的异步编码方式,类似于Java中的Future对象。
let p = new Promise((resolve, reject) => {
// 在方法里进行操作,然后根据情况调用resolve,或者reject方法。
if (相关条件) {
resolve()
} else {
reject()
}
})
p.then(() => {
// 如果我们调用了resolve方法,则调用本方法
}).catch(() => {
// 如果我们调用了reject方法,则调用本方法
})
Promise类型构造函数只有一个函数类型的参数,Promise对象在构造之后会直接被异步运行,通常我们称为起始函数。在起始函数中包含两个参数 resolve 和 reject,这两个参数类型都是函数。
- resolve参数代表函数执行正常
- reject参数代表函数执行出错
Promise类型提供了三个处理方法,then、catch、finally方法,很类似于我们通常的错误处理流程:try-catch。我们将正常的执行代码放置then方法中,异常处理代码放置catch中,资源等收尾代码放置finally中(finally方法总是会被执行)。
例如下面的例子代码:
new Promise( (resolve, reject) => {
console.log( "Go" );
resolve("调用then方法")
} ).then((resolve)=>{
console.log( "then接受参数",resolve );
}).catch((reject)=>{
console.log( "catch",reject );
}).finally(()=>{
console.log("执行finally")
})
// Go
// then接受参数 调用then方法
// 执行finally
从上面的代码也可以看到,Promise是链式调用方式,同时then也可以定义多次,会按照定义顺次来顺序执行,catch也可以定义多次不过只会执行第一个catch方法。
new Promise( (resolve, reject) => {
console.log( "Go" );
resolve("调用then方法")
} ).then((resolve)=>{
console.log( "then1接受参数",resolve ); // 当我们需要创建一个新的Promise对象时,就可以在定义一个新的then方法,用于处理。
return new Promise((r1)=>{
r1("调用then2方法")
})
}).then((resolve)=>{
console.log( "then2接受参数",resolve );
}).then((resolve)=>{
console.log( "then3接受参数",resolve );
})
// Go
// then1接受参数 调用then方法
// then2接受参数 调用then2方法
// then3接受参数 undefined
Promise状态
一个promise对象必定处于三种状态之一:
- 待定(pending):初始状态,既对象被刚刚创建,没有调用
resolve或者reject这任何一个方法。 - 已执行(fulfilled):即操作已经完成。
- 已拒绝(rejected):即操作失败被拒绝。
小细节
-
在起始函数中调用了resolve或者reject方法后,起始函数并不会停止运行的,如果要停止需要注意return。
new Promise( (resolve, reject) => { console.log( "开始" ); resolve("调用then方法") // 需要在下一行添加return语句 console.log( "不应该被执行" ); } ) // 开始 // 不应该被执行