前言
ES6 中的一个内容 Promise,鉴于内容有点长就另开一篇。
正文
Promise的构造:
const pr = new Promise((resolve, reject) => {});
Promise的三种状态:
const pr = new Promise((resolve, reject) => {});
console.dir(pr);
Promise状态的改变:
const pr = new Promise((resolve, reject) => {
resolve("成功");
});
console.dir(pr);
const pr = new Promise((resolve, reject) => {
reject("失败");
});
console.dir(pr);
const pr = new Promise((resolve, reject) => {
resolve("成功");
reject("失败");
});
console.dir(pr);
Promise的then方法:
补充一点,每个对象在被创建的时候都是有一个原型的,并通过prototype属性与原型进行关联,可以看到上面控制台中每个Promise都有这样一个属性; then方法就是其关联原型的一个方法;
const pr = new Promise((resolve, reject) => {
resolve("成功");
});
pr.then((value) =>{
console.log(value);
},(reason) =>{
console.log(reason);
});
console.dir(pr);
const pr = new Promise((resolve, reject) => {
reject("失败");
});
pr.then((value) =>{
console.log(value);
},(reason) =>{
console.log(reason);
});
console.dir(pr);
当Promise的状态为fulfilled时,将resolve的参数传递给then的第一个函数,并执行第一个函数; 当Promise的状态为rejected时,将reject的参数传递给then的第二个函数,并执行第二个函数;
const pr = new Promise((resolve, reject) => {
});
console.dir(pr.then((value) =>{},(reason) =>{}));
const pr = new Promise((resolve, reject) => {
resolve("成功");
});
const pr_1=pr.then((value) =>{
console.log(value);
return "成了";
},(reason) =>{
console.log(reason);
return "错了";
});
console.dir(pr_1);
const pr = new Promise((resolve, reject) => {
reject("成功");
});
const pr_1=pr.then((value) =>{
console.log(value);
return "成了";
},(reason) =>{
console.log(reason);
return "错了";
});
console.dir(pr_1);
then的链式结构:
const pr = new Promise((resolve, reject) => {
reject("成功");
});
const pr_1=pr.then((value) =>{
console.log(value);
return value;
},(reason) =>{
console.log(reason);
return reason;
});
const pr_2=pr_1.then((value) =>{
console.log(value);
return value;
},(reason) =>{
console.log(reason);
return reason;
});
console.log(pr_2);
catch方法:
const pr = new Promise((resolve, reject) => {
reject("出错了");
});
pr.catch((reason) =>{
console.log(reason);
})
const pr = new Promise((resolve, reject) => {
throw new Error("出错了");
});
pr.catch((reason) =>{
console.log(reason);
})
const pr = new Promise((resolve, reject) => {
console.log(a);
});
pr.catch((reason) =>{
console.log(reason);
})
关于Promise就介绍到这里,想要了解更多方法可以搜索 Promise A+;
|