Promise首先基于了一个JS引擎的执行机制原理:https://segmentfault.com/a/1190000012806637
1.Promise具有不受外界影响和不可逆的特点,只要执行了resolve就不执行第二个了,只能执行一个。
new Promise(function(resolve,reject){
resolve();
reject();
}).then(function(){
alert("成功的方法!")
}).catch(function(){
alert("失败之后调用的方法!");
})
2.Promise链式调用,当执行完then时还想让它在执行一个方法,就要用到----------链式调用,不满足的话可以多次调用
new Promise(function (resolve,reject){
resolve("成功");
reject("失败");
}).then(function(v){
alert(v);
return "123";
}).then(function(v){ // 这个参数就是上一个then返回的值。
alert(v);
return "再来一个,哈哈!";
}).then(function(a){
alert(a);
})
3.3.Promise的静态方法(很少用到)
// 成功的时候可以用这个方法
Promise.resolve("静态方法没啥用,只是有这个功能而已!").then(function(m){
alert(m);
})
// 失败的时候也可以用这个方法
Promise.reject("静态方法也是没有什么用,面试的时候吹牛逼吧,哈哈!").catch(function(m){
alert(m);
})
4.race--- 方法:一堆promise实例,谁先过来我就先算谁的,先成功--->成功, 先失败--->失败;如果先执行失败的方法那么成功的方法就不执行了。
Promise.race([new Promise(function(resolve,reject){
setTimeout(resolve,301,'one');
}),new Promise(function(resolve,reject){
setTimeout(resolve,300,'two');
}),new Promise(function(resolve,reject){
setTimeout(reject,100,'three');
})]).catch(function(l){
console.log(l)
})
5.把所有的东西放到数组里并且展示出来.Promise.all
Promise.all([Promise.resolve('abc'),Promise.reject('def'),2,3]).then(
function(m){
console.log(m);
}
).catch( // 因为有一个失败的,所以说只执行失败的方法,并且把失败的东西返回来。
function (m){
console.log(m);
}
)
网友评论