/* * @Author: Rindy * @Date: 2021-08-13 12:00:10 * @LastEditors: Rindy * @LastEditTime: 2021-08-13 15:32:02 * @Description: 兼容jQuery.Deferred :( */ const noop = function () {} Promise.prototype.done = Promise.prototype.then Promise.prototype.fail = Promise.prototype.catch class Deferred { constructor() { this._resolve = [] this._reject = noop this._notify = noop this._progress = noop this._state = 'pending' } state() { return this._state } done(resolve) { this._resolve.push(resolve) return this } fail(reject) { this._reject = reject return this } then(resolve) { this._resolve.push(resolve) return this } catch(reject) { this._reject = reject return this } notify(...args) { this._notify = [...args] if (typeof this._progress == 'function') { this._progress.apply(null, this._notify) } return this } when(...args) { Promise.all([...args]) .then((...args) => { this._state = 'resolve' this._resolve.forEach(item => item(...args)) }) .catch((...args) => { this._state = 'reject' this._reject(...args) }) } progress(callback) { this._progress = callback return this } resolve(result) { this._state = 'resolve' return Promise.resolve().then(() => this._resolve.forEach(item => item(result))) } reject(result) { this._state = 'reject' return Promise.reject().catch(() => this._reject(result)) } promise() { return this } } export default function () { return new Deferred() }