美文网首页
手写promise

手写promise

作者: 东门不吹雪 | 来源:发表于2019-06-19 09:39 被阅读0次

    面试的笔试题中遇到过手写promise的题目,以下是参考了网上的文章,自己整理的一个简单的promise函数:

    function Promise(executor) {
        let self = this;
        self.status = 'pending';
        self.value = 'undefined';
        self.reason = 'undefined';
    
        function resolve(value) {
            if(self.status === 'pending') {
                self.status = 'resolve';
                self.value = value;
            }
        }
    
        function reject(reason) {
            if(self.status === 'pending') {
                self.status = 'reject'
                self.reason = reason
            }
        }
        try {
            executor(resolve,reject)
        } catch {
            reject(e)
        }
    }
    
    Promise.prototype.then = function (onFulfilled,onRejected) {
        let self = this
        if(self.status === 'resolve') {
            onFulfilled(self.value)
        } else {
            onRejected(slef.reason)
        }
    }
    module.exports = Promise
    
    

    相关文章

      网友评论

          本文标题:手写promise

          本文链接:https://www.haomeiwen.com/subject/ehfhqctx.html