美文网首页javaScript
javaScript--promise

javaScript--promise

作者: 反者道之动001 | 来源:发表于2017-07-05 23:53 被阅读12次

努力让异步一点也不麻烦

pending 状态

很简单的例子:

var promise = new Promise(function(resolve, reject){
    //执行成功时调用resolve, 当失败调用reject
    setTimeout(function(){
        resolve("ok!"); //代码正常执行!
    }, 1000);
});

promise.then(function(msg){
    console.log(successMessage);// ok
});

自己模拟一下上面的效果

    // XXY version of promise
    window.Xxythen = function(instantiation){
        var then = []
        // subscription
        function on(param){
            then.push(param)
        }
        // publish
        function reject(){
            console.error('[then end]')
        }
        function resolve(e){
            then.forEach(function(re){
                re(e)
            })
        }
        instantiation(resolve,reject)
        return {
            then: param=>{
                on(param)
            }
        }
    }
    
    // instantiation
    var xxythen = new Xxythen((resolve,reject)=>{
        window.setTimeout(function(){
            resolve(0)
        },2000)
    })
    
    xxythen.then((a)=>{
        console.log(a)
    })
    xxythen.then((a)=>{
        console.log(a)
    })

OK,完美,promise的用处远远不止这些,先写这些,日后再更新。

相关文章

  • javaScript--promise

    努力让异步一点也不麻烦 很简单的例子: 自己模拟一下上面的效果 OK,完美,promise的用处远远不止这些,先写...

网友评论

    本文标题:javaScript--promise

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