基础Promise
new Promise (
function (resolve,reject) {
resolve(); // 决定做
reject(); // 放弃做
}
).then(
function () { // 决定做执行的函数
alert(1);
},
function () { // 放弃做执行的函数
alert(2);
}
)
Promise对象拥有.then()方法,接收两个函数,函数的执行受Promise函数体的方法决定
带数据传递的Promise
new Promise(function (resolve,reject){
resolve('success');
}).then(function(item){
if (item) {
return `暴露item:${item}`;
}
}).then(function(res){
console.log(res);
})
.then()方法可以return一个数据,作为下一个.then()的参数
带catch
的Promise
new Promise(function (resolve,reject){
resolve('success');
}).then(function(item){
if (item) {
return `暴露item:${item}`;
}
}).then(function(res){
if (!res) {
throw `未能拿到预期的值,值为:${res}`; // throw可以搭配catch使用
}
}).catch(function(err){
console.log(err);
})
每次return
都会创建一个新的Promise对象,都用于独立的.then()、.catch()方法
new Promise(function (resolve,reject){
resolve('success');
}).then(function(item){
if (item) {
return `暴露item:${item}`;
}
}).then(function(res){
if (!res) {
throw `未能拿到预期的值,值为:${res}`;
}
}).catch(function(err){
return err;
}).then(function () {
console.log(err);
})
Promise
静态方法
Promise.resolve(res).then(
function(res){
console.log(res)
})
Promise拥有自己的静态方法
race
竞速竞赛,相当于||
Promise.race([new Promise(function (resolve,reject){
setTimeout(resolve,500,'one');
}),new Promise(function (resolve,reject){
setTimeout(resolve,500,'two');
}),new Promise(function (resolve,reject){
setTimeout(reject,500,'three');
})]).then(function(res){
console.log(res)
}).catch(function(err){
console.log(err)
})
一堆的promise 实例,谁先过来我就先算谁的,先成功即返回成功,先失败即返回失败,只要有一个结果就不会向下执行了
all
所有的类型 ,只要有失败的 ,就会走catch,相当于&&
Promise.all([Promise.resolve('abc'),Promise.resolve('bcd'),3])
.then(
function(res){
console.log(res)
})
.catch(
function(err){
console.log(err)
})
配合async
await
使用
async function fetchUsers(){
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
console.log(data);
}
fetchUsers()
只有在一个await执行完成后才会向下执行