zoukankan      html  css  js  c++  java
  • 迷你版Deferred

    直接贴代码:

    /**
     * 迷你版的deferred
     */
    function Deferred(func) {
        if (this instanceof Deferred === false) {
            return new Deferred(func)
        }
        var tuple = [];
        var promise = {
            resolve: function () {
                var t;
                while (t = tuple.shift()) {
                    t.apply(null, arguments);
                }
            },
            then: function (n) {
                return tuple.push(n), this;
            }
        }
        if (func) {
            func.call(promise, promise.resolve);
        }
        return promise;
    }

    demo1:

    var d = new Deferred();
    
    setTimeout(function () {
        d.resolve({
            name : 'breezefeng',
            age : 24,
            sex : '男'
        });
    });
    
     d.then(function (globalInfo) {
        console.log(globalInfo.name);
    }).then(function (globalInfo) {
        console.log(globalInfo.age);
    }).then(function (globalInfo) {
        console.log(globalInfo.sex);
    });

    demo2:

    Deferred(function (resolve) {
        setTimeout(function () {
            resolve('aaaa');
        });
    }).then(function (bbb) {
        console.log(bbb)
    })
  • 相关阅读:
    D3 data
    cubism.js
    git
    Render函数
    Vue 响应式原理
    JSSDK使用步骤
    用js获取access_token
    微信公众平台appid和appsecret在哪
    组件
    表单控件绑定
  • 原文地址:https://www.cnblogs.com/fengyuqing/p/deferred-mini.html
Copyright © 2011-2022 走看看