js 如何取消promise

1: 使用reject

function hello() {
  let _res, _rej: any;

  const promise = new Promise((res, rej) => {
    _res = res;
    _rej = rej;
    setTimeout(() => {
      res("hello world");
    }, 5000);
  });
  return {
    promise,
    abort: (opt = {}) => {
      _rej({
        name: "abort",
        message: "the promise is aborted",
        aborted: true,
        ...opt
      });
    }
  };
}

const { promise, abort } = hello();
promise.then(console.log).catch(e => {
  console.log(e);
});

abort();

2: 使用Promise.race

const promise = new Promise(function(res) {
  setTimeout(res, 5000, "hello world");
});

const abort = new Promise(function(_, _abort) {
  _abort({
    name: "abort",
    message: "the promise is aborted",
    aborted: true
  });
});

Promise.race([promise, abort])
  .then(console.log)
  .catch(e => {
    console.log(e);
  });

使用rxjs

import { from } from "rxjs";

function hello() {
  return new Promise(res => {
    setTimeout(() => {
      res("hello world");
    }, 5000);
  });
}

const hello$ = from(hello()).subscribe(
  console.log,
  er => {
    console.error(er);
  },
  () => {
    console.log("done");
  }
);

hello$.unsubscribe();
posted @ 2020-03-18 11:17  Ajanuw  阅读(3589)  评论(0编辑  收藏  举报