emmm... 这块内容 "肥肠" 重要(不是)哦~
前言
基本语法
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("hello 摸鱼佬🐠")
// reject("🐛🐛🐛")
}, 1000);
});
promise.then(
(res) => {
console.log(res);
},
(reason) => {
console.log(reason);
}
);
promise.catch((error) => {
console.log(error);
});
!! 一旦被new,promise就会自动执行
内部属性
!! 无法直接访问,可使用then或catch捕获结果
- state
pending - 初始状态
fullfilled - resolve后的状态
rejected - reject后的状态
- result
最初是undefined
resolve(value)变为value
reject(error)变为error
捕获结果
then
特点: 在promise被settled时执行
promise.then((value)=>{
//接收resolve后的结果
},(reason)=>{
//接收reject后的结果
})
catch
特点: 链上没处理错误则catch会去处理
和then的第二个参数是否相等呢?
- then出现错误的时候就是catch去处理,还是有点不同滴😜
promise.catch((reason)=>{
//then未处理reject的错误,catch可以捕获到
})
finally
const promise = new Promise((resolve, reject) => {
resolve(1);
});
promise
.finally(() => {
//没有参数,返回值会被忽略,先执行这个语句
console.log("怎么回事,小老弟");
return '哈哈哈'
})
.then((res) => {
//如果是resolve,后执行这个
console.log(res);
});
结果打印:
怎么回事,小老弟
1
链式调用
错误示范,这个可不是链式调用,这只是多次订阅promise
const promise = new Promise((resolve, reject) => {
resolve(1);
});
promise.then((res) => {
console.log(res);//1
});
promise.then((res) => {
console.log(res);//1
});
链式调用示例:
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 1000);
})
.then((count) => {
console.log(count);//1
return ++count;
})
.then((count) => {
console.log(count);//2
return ++count;
})
.then((count) => {
console.log(count, "end");//3 end
});
异步的要怎么弄呢,整起 (这不就解决了回调地狱问题)
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 1000);
})
.then((count) => {
console.log(count);//1
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(++count);
}, 1000);
});
})
.then((count) => {
console.log(count);//2
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(++count);
}, 1000);
});
}).then((count) => {
console.log(count,'end');//3 end
})
相关的API
Promise.all
特别:
- 传入一个可迭代对象例如数组,返回一个promise
- 有顺序,传入一个promise数组,返回的promise resolve的结果也是按数组元素排列的
- 如果时传入promise数组,有一个出错即reject,则全体reject并返回reject的错误信息
Promise.allSettled(ES2020)
如果时promise数组,某个promise被reject,其他promise照常settled,并返回promise
Promise.race
只等待第一个settled的promise
Promise.any
只等待一个fullfilled的promise
Promise.resolve
创建一个resolve的promise
Promise.reject
创建一个reject的promise
Promise.withResolvers(新特性)
返回一个对象包含新的promise对象、resolve和reject函数
class NotPromise {
name;
constructor(executor) {
name = "kitty";
executor(
(value) => console.log("Resolved", value),
(reason) => console.log("Rejected", reason)
);
}
say() {
return name;
}
}
const { promise, resolve, reject } =
Promise.withResolvers.call(NotPromise);
reject("hello"); // Resolve hello
console.log(promise.say()); // kitty
PromiseA+
class MyPromise {
static PENDING = 'pending';
staticFULFILLED = 'fulfilled';
static REJECTED = 'rejected';
constructor(executor) {
this.state = MyPromise.PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === MyPromise.PENDING) {
this.state = MyPromise.FULFILLED;
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback());
}
};
const reject = (reason) => {
if (this.state === MyPromise.PENDING) {
this.state = MyPromise.REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
const promise2 = new MyPromise((resolve, reject) => {
if (this.state === MyPromise.FULFILLED) {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
} else if (this.state === MyPromise.REJECTED) {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
} else if (this.state === MyPromise.PENDING) {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called = false;
if ((x !== null && typeof x === 'object') || typeof x === 'function') {
try {
const then = x.then;
if (typeof then === 'function') {
then.call(
x,
y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
},
r => {
if (called) return;
called = true;
reject(r);
}
);
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
resolve(x);
}
}
// 示例用法
const p = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
p.then(value => {
console.log(value); // 'Success!'
return 'Next success!';
}).then(value => {
console.log(value); // 'Next success!'
}).catch(error => {
console.error(error);
});
最后
对promise的理解深刻有助于我们更好地理解和实现自定义函数、封装接口请求和异步处理