xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript Promise.withResolvers API All In One

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/ 查看原创文章!

AbortController

signal

let controller;

function fetchVideo() {
  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then(response => {
      console.log('Download complete', response);
    })
    .catch(err => {
      console.log('Download error: ' + err.message);
    });
}

使用 AbortController API 实现 debounce 防抖效果 ✅

// 外部变量
let controller;
const url = "video.mp4";
// const url = "https://mdn.github.io/dom-examples/abort-api/sintel.mp4";
const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');
abortBtn.addEventListener('click', function() {
  if (controller) {
    controller.abort();
    console.log('Download aborted');
  }
});
downloadBtn.addEventListener('click', fetchVideo);

function fetchVideo() {
  // 外部变量赋值
  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then(function(res) {
      console.log('Download complete', res.text());
    })
    .catch(function(err) {
      console.log('Download error: ' + err.message);
    });
}

image

https://mdn.github.io/dom-examples/abort-api/

https://developer.mozilla.org/en-US/docs/Web/API/AbortController

refs

https://webdeveloper.beehiiv.com/p/cancel-promises-javascript

https://www.cnblogs.com/xgqfrms/p/16028578.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2024-07-16 12:29  xgqfrms  阅读(18)  评论(2编辑  收藏  举报