简单的Promise

强颜欢笑 提交于 2020-04-07 21:51:57
function MYPromise(fn) {
    var self = this
    self.onResolvedCallback = []
    function resolve(value) {
        setTimeout(() => {
            self.data = value
            self.onResolvedCallback.forEach(callback => callback(value))
        })
    }
    fn(resolve)
}
MYPromise.prototype.then = function (fn) {
    var self = this
    return new MYPromise(resolve => {
        self.onResolvedCallback.push(function () {
            var result = fn(self.data)
            if (result instanceof MYPromise) {
                result.then(resolve)
            } else {
                resolve(result)
            }
        })
    })
}

  

参考文章:https://juejin.im/post/5e6f4579f265da576429a907#heading-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!