javaScript--promise

努力让异步一点也不麻烦

javaScript--promise_第1张图片
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)