- 什么是promise
Promise:是个对象类似于一个事情;就会有成功或者失败只要触发一个这个函数就完成了自己的任务;有两种写法;
第一种写法:
new Promise((resolved,reject)=>{
resolved()//这个地方如果是resolved()打印的是1如果是reject()打印的就是2
}).then(()=>{
console.log(1)
},()=>{
console.log(2)
})
第二种写法:
new Promsie((resolved,reject)=>{
resolved()//这个地方如果是resolved()打印的是1如果是reject()打印的就是2
}).then(()=>{
console.log(1)
}).catch(()=>{
console.log(2)
})
- promise封装案例:
function showPromise(str){
return new Promise((res,rej)=>{
res(str)
}).then((x)=>{
console.log(x)
}).catch((err)=>{
console.log(err)
})
}
showPromise('a')
-
race():
竞速方法,只看第一个promise成功就成功失败就失败;
//promise.race()属性:(两个或者多个promise运行,那个走的快就返回那个)
Promise.race([new Promise((res,rej)=>{
res(1)
}),new Promise((res,rej)=>{
res(2)
})]).then((x)=>{
console.log(x)
}).catch(()=>{})
- all()方法
all()都成功了才会进行成功如果有一个失败了就会进行失败
Promise.all([new Promise((res,rej)=>{
res()
}),new Promise((res,rej)=>{
res()
})]).then(()=>{
console.log(1)
}).catch(()=>{
console.log(2)
})
- prmoise的成功和失败方法
Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的promise 对象。
Promise.reject方法允许调用时不带参数,直接返回一个rejected的promise对象。