new Promise
// 创建一个promise
let pro = new Promise((resolve, reject) => {
// 做一些事情(进行状态)
if (/*当满足某个条件*/) {
resolve(一些数据) // 调用resolve函数 (由进行转变到成功状态)
} else(/*即不满足条件*/){
reject(错误) // 调用rejected函数(由进行转变到失败状态)
}
})
// 使用这个promise
pro.then((一些数据) => {
// 这里写resolve函数的具体实现
}, (错误) => {
// 这里写reject函数的具体实现
})
//
let p1=new Promise((res,rej)=>{
res("sss")
}).then(res=>{
console.log(res); //sss
return "sxc"
}).then(res=>{
console.log(res); //sxc
})
console.log(p1); //Promise {<pending>} Promise构造函数
我们使用 Promise 这个构造函数来创建一个promise,new Promise ((resolve, reject) 则是一个规定的写法,当promise内部满足某个条件时会调用resolve函数,同时可以传递一些参数进去(此时promise的状态由 进行 => 成功)。当不满足条件时会调用reject函数,也可以传递一些参数进行,一般传递的是错误信息(此时promise的状态由 进行 => 失败))。
而成功的resolve函数及失败的reject函数我们则是在用 .then 使用promise的时候再写好,.then是一种链式操作,可以多次调用: 使用then方法接收后,可以继续用then方法调用,再次调用所获取的参数是上个then方法return的内容。
Promise.race
let p1=new Promise((res,rej)=>{
res("sss")
})
let p2=new Promise((res,rej)=>{
res("fff")
})
Promise.race([p2,p1]).then(res=>{
console.log(res); //fff
}).catch(err=>{
console.log(err);
})
// 传入空数组无输出,因为要返回第一个promiss对象
Promise.race([]).then(res=>{
console.log("ALL");
}).catch(err=>{
console.log("ERR");
})
Promise.all
let p1=new Promise((res,rej)=>{
res("sss")
})
let p2=new Promise((res,rej)=>{
res("fff")
})
Promise.all([p2,p1]).then(res=>{
console.log(res); // ['fff', 'sss']
}).catch(err=>{
console.log(err);
})
//
let p1=new Promise((res,rej)=>{
res("sss")
})
let p2=new Promise((res,rej)=>{
rej("fff")
})
Promise.all([p2,p1]).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err); //fff
})
//传入空数组执行成功的语句,因为代表所有的promiss对象都成功
Promise.all([]).then(res=>{
console.log("ALL"); //ALL
}).catch(err=>{
console.log("ERR");
})
Promise.all和Promise.race方法区别:
Promise.all:
1,有一个失败的请求,其他都失败; Promise.all()将多个Promise放在一个数组中,当整个数组的全部promise成功时才会返回成功,返回结果的顺序按照参数的顺序进行;当数组中的promise有一个出现失败时就只返回失败 (失败的结果是第一个失败的promise结果)。
2.当传入一个空数组的时候,Promise.all会执行then语句,而Promise.race都不会执行
3.正常是传入一个数组,如果传入number型的数值或者不传入值,all和race都会执行catch语句,如果传入任何字符串类型的值,两者都会执行then语句
Promise.race:
1,根据第一个请求来返回结果,若第一个成功,全局都成功,第一个失败,全局都失败;
2,返回结果的顺序,按请求时间顺序来,时间快的先返回,只返回第一个结果;