promise的简单使用
简介
- Promise 对象是一个代理对象(代理一个值),被代理的值在Promise对象创建时可能是未知的。
- 它允许你为异步操作的成功和失败分别绑定相应的处理方法(handlers),这让异步方法可以像同步方法那样返回值,用一个能代表未来出现的结果的promise对象代表返回值
promise的状态:
- pending:初始状态,既不是成功也不是失败状态。
- resolve:操作成功。
- rejected:操作失败。
关于回调地域
- 什么是回调地狱?
- Javascript是单线程的,而Javascript的异步执行中,就会出现回调地狱。
- 回调地狱,函数作为参数层层嵌套,层级很深,使得代码看起来很混乱。
function test1(function test2(){
test3(function test4(){
//....
})
})
promise是Javascript的一种异步解决方案
- promise自顶向下执行
- promise鼓励使用try/catch样式错误处理,而使之能处理更多错误类型
简单使用
const myFirstPromise = new Promise((resolve, reject) => {
resolve(someValue); // resolve
reject("failure reason"); // rejected
}).then(res=>{
}).catch(err =>{
})
promise的特点
- Promise的状态一旦发生改变便无法更改
new Promise(function(resolve,reject){
resolve('123')
reject('123')
}).then(function(res){
console.log(res)
}).catch(function(err){
console.log(err)
})
上述事例中,在promise里的回调里面执行了resolve(‘123’)后,promise的状态就发生了改变,即不会再往后执行reject(‘123’),原因是在promise状态发生了改变以后就不会在进行改变,即[promiseStatus]为resolve。Promise的状态不可逆。
- Promise的传入期望是一个函数,传入非函数会发生值穿透
new Promise(function(resolve,reject){
resolve('123')
}).then('24141234').then(function(res){
console.log(res)
//123
})
上述事例中,在当promise的then是一个字符串(非函数)的时候,它会发生值穿透,即返回的参数123会穿透到接下来的不是非函数的then的回调里面。
- Promise的回调是同步的,而then的回调是异步的
new Promise(function(resolve,reject){
console.log('0')
console.log('123')
resolve('789')
console.log('456')
}).then(function(res){
console.log(res)
}).catch(function(err){
console.log(err)
})
/* 打印结果
0
123
456
789
*/
上述事例中,在promise的回调函数中执行是同步的,所以先输入0,后输出123。
而到执行resolve的时候即会执行then,将789作为参数,但是由于then的执行是一个异步操作,所以会产生一定的延时,所以,会先打印出456,在打印出789。
- 链式调用then,上一个then的返回值,是下一个then接收的参数,如果返回错误,返回一个状态为reject的promise
new Promise(function(resolve,reject){
resolve('jacky')
}).then(function(res){
return 'my '+res
}).then(function(res){
console.log(res)
})
/* 打印结果
my jacky
*/
链式调用then,上一个then的返回值,是下一个then接收的参数
new Promise(function(resolve,reject){
resolve('jacky')
}).then(function(res){
return new Error('This is a error')
}).then(function(res){
console.log('then:',res)
}).catch(function(err){
console.log('catch:',err)
})
/* 打印结果
then: Error: This is a error
*/
new Promise(function(resolve,reject){
resolve('jacky')
}).then(function(res){
throw new Error('This is a error')
}).then(function(res){
console.log('then:',res)
}).catch(function(err){
console.log('catch:',err)
})
/* 打印结果
catch: Error: This is a error
*/
上述事例中:
如果用return返回错误,则会返回一个正常的promise,即执行下一个then回调
如果用throw抛出错误,返回一个状态为reject的promise,即执行下一个catch回调
- then的回调里return一个promise会进入等待状态,直到return的promise改变
new Promise(function(resolve,reject){
resolve('jacky')
}).then(function(res){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('5')
},4000)
})
}).then(function(res){
console.log('then:',res)
}).catch(function(err){
console.log('catch:',err)
})
/* 打印结果 等待5秒后打印
then: 5
*/
上述事例中: 只有返回的promise的状态发生改变了(变为resolve或者reject)才会执行下面的then或者catch,不然就一直等待。