Promiss
状态:
- pending:[待定]初始状态
- fulfilled:[实现]操作成功
- rejected: [被否决]操作失败
基本用法
//普通定义
let ajax = (callback) => {
console.log('≈')
setTimeout(() => {
callback && callback.call();
}, 1000)
}
ajax(() => {
console.log('timeout')
})
// 先会打出 开始执行,1s 后打出 timeout
//Promise
let ajax = () => {
console.log("开始执行");
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
};
ajax().then(() => {
console.log("timeout");
});
// 先会打出 开始执行,1s 后打出 timeout
// then()
let ajax = () => {
console.log("开始执行");
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
};
ajax()
.then(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
})
.then(() => {
console.log("timeout")
})
// 先会打出 开始执行,3s(1+2) 后打出 timeout
// catch()
let ajax = (num) => {
console.log("开始执行");
return new Promise((resolve, reject) => {
if (num > 5) {
resolve();
} else {
throw new Error("出错了");
}
});
};
ajax(6)
.then(function () {
console.log("timeout"); // 先会打出 开始执行,1s 后打出 timeout
})
.catch(function (err) {
console.log("catch", err);
});
ajax(3)
.then(function () {
console.log("timeout");
})
.catch(function (err) {
console.log("catch"); // 先会打出 开始执行,1s 后打出 catch
});
Promise.all() 批量操作
//所有图片加载完成后添加到页面
const loadImg = (src) => {
return new Promise(resolve, reject) => {
let img = document.createElement("img");
img.src = src;
img.onload = function () {
resolve(img);
};
img.onerror = function (err) {
reject(err);
};
});
}
const showImgs = (imgs) => {
imgs.forEach((img) => {
document.body.appendChild(img);
})
}
Promise.all([
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
]).then(showImgs);
Promise.race()
//有一个执行完就回加载到页面
const loadImg = (src) => {
return new Promise(resolve, reject) => {
let img = document.createElement("img");
img.src = src;
img.onload = function () {
resolve(img);
};
img.onerror = function (err) {
reject(err);
};
});
}
const showImgs = (imgs) => {
let p = document.createElement("p");
p.appendChild(img);
document.body.appendChild(p);
}
Promise.race([
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"),
]).then(showImgs);
Promise.finally()
let func = time => {
return new Promise((res, rej) => {
setTimeout(() => {
if(time < 500){
res(time)
}else{
rej(time)
}
}, time)
})
}
func(300)
.then((val) => console.log('res', val))
.catch((erro) => console.log('rej', erro))
.finally(() => console.log('完成'))
// 执行结果: res 300 完成
func(700)
.then((val) => console.log('res', val))
.catch((erro) => console.log('rej', erro))
.finally(() => console.log('完成'))
// 执行结果: rej 700 完成
for-await-of
let getTime = (seconds) => {
return new Promise(res => {
setTimeout(() => {
res(seconds)
}, seconds)
})
}
async function test(){
let arr = [getTime(2000),getTime(500),getTime(1000)]
for await (let x of arr){
console.log(x);
}
}
test() //以此执行 2000 500 1000
Promise.allSettled()
Promise.allSettled([
Promise.reject({
code: 500,
msg: "服务异常",
}),
Promise.resolve({
code: 200,
data: ["1", "2", "3"],
}),
Promise.resolve({
code: 200,
data: ["4", "5", "6"],
}),
]).then((res) =>{
console.log(res) // [{ reason: {code: 500, msg: '服务异常'}, status: "rejected" },
// { reason: {code: 200, data: ["1", "2", "3"]}, status: "rejected" },
// { reason: {code: 200, data: ["4", "5", "6"]}, status: "rejected" }]
const data = res.filter((item) => item.status === "fulfilled");
console.log(data); // [{ reason: {code: 200, data: ["1", "2", "3"]}, status: "rejected" },
// { reason: {code: 200, data: ["4", "5", "6"]}, status: "rejected" }]
})
Promise.any()
Promise.any([
Promise.reject("Third"),
Promise.resolve("Second"),
Promise.resolve("First"),
])
.then((res) => console.log(res)) // Second
.catch((err) => console.error(err));
Promise.any([
Promise.reject("Error 1"),
Promise.reject("Error 2"),
Promise.reject("Error 3"),
])
.then((res) => console.log(res))
.catch((err) => console.error(err));
// AggregateError: All promises were rejected
Promise.any([
Promise.resolve("Third"),
Promise.resolve("Second"),
Promise.resolve("First"),
])
.then((res) => console.log(res)) // Third
.catch((err) => console.error(err));
递进(依赖上一个函数结果)+.all()
queryEntry() {
this.loading = true;
new Promise((resolve, reject) => {
return this.queryFirstStep(resolve);
}).then((resolve, reject) => {
return this.querySecondStep(resolve);
}).then((data) => {
return this.queryThirdStep();
});
},
queryFirstStep(resolve) {
axios.get(url, query).then(res => {
// do something
resolve(res);
})
},
querySecondStep(resolve){
axios.get(url, query).then(res => {
// do something
resolve(res);
})
},
queryThirdStep(){
axios.post(url, param).then(res => {
// do something
})
}