← 返回首页
什么是PromiseLike
发表时间:2023-02-11 12:02:15
什么是PromiseLike

在Promise官方标准出现之前有许多类似的Promise实现,Typescript为了区分二者的区别:一个叫Promise,一个叫Promise Like.

1.Promise Like

Promise Like顾名思义就是像Promise的实现。那么什么是Promise呢?

简单一句话:promise是一个拥有then方法的对象或函数。

下面是官方对Promise的定义:

/**
 * Represents the completion of an asynchronous operation
 */
interface Promise<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
/**
 * Represents the completion of an asynchronous operation
 */
interface Promise<T> {
    /**
     * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
     * resolved value cannot be modified from the callback.
     * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
     * @returns A Promise for the completion of the callback.
     */
    finally(onfinally?: (() => void) | undefined | null): Promise<T>
}

2.如何判断一个值是否是PromiseLike

简单说就是编写一个函数判断是否符合Promise A+规范即可。

/*
  判断一个值是否是PromiseLike
*/

function isPromiseLike(value){

    return (
        value!=null && 
        (typeof value === 'object' || typeof value === 'function') &&
        typeof value.then === 'function'  
    )
}