JavaScript Promise.withResolvers API All In One
Promise.withResolvers()
// 使用解构的方式,更优雅的自动获取内部的 resolve, reject 方法 ✅
const {promise, resolve, reject } = new Promise.withResolvers();
// 等价于, 使用外部变量,手动赋值引用内部 resolve, reject 方法 💩
let resolve, reject;
const promise = new Promise((res, rej) => {resolve = res;reject = rej;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
demos
cancelable Promise / cancel Fetch request
const cancelablePromise = <T>(asyncFn: () => Promise<T>) => {let rejected = false;const { promise, resolve, reject } = Promise.withResolvers<T>();return {run: () => {if (!rejected) {asyncFn().then(resolve, reject);}return promise;},cancel: () => {rejected = true;reject(new Error('CanceledError'));},};
};// test
const sleep = (ms: number) => new Promise(res => setTimeout(res, ms));const demo = cancelablePromise(async () => {await sleep(1000);return 'Hello';
});// IIFE
(async () => {try {const value = await ret.run();console.log('value =', value);} catch (err) {console.log('erroe = ', err);}
})();setTimeout(() => {demo.cancel();
}, 500);
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://webdeveloper.beehiiv.com/p/cancel-promises-javascript
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!