Promise实现简易AMD加载器

在最新的Chrome和FF中已经 实现了Promise。有了Promise我们用数行代码即可实现一个简易AMD模式的加载器

Promise实现简易AMD加载器
var registry = {
    promises: { },
    resolves: { },
    getDependencyPromise: function(name) {
        if (!this.promises[name]) {
            var resolves = this.resolves;
            this.promises[name] = new Promise(function(resolve, reject) {
                resolves[name] = resolve;
            });
        }
        return this.promises[name];
    },
    resolve: function(name, value) {
        this.getDependencyPromise(name); // creates promise if necessary
        this.resolves[name](value);
        delete this.resolves[name];
    }
};

function define(name, deps, definition) {
    require(deps, function() {
        registry.resolve(name, definition.apply(this, arguments));
    });
}

function require(deps, definition) {
    var promises = deps.map(registry.getDependencyPromise, registry);
    Promise.all(promises).then(function(result) {
        definition.apply(this, result);
    });
}
Promise实现简易AMD加载器

使用方式如下

 

Promise实现简易AMD加载器
define(‘framework‘, [‘component‘, ‘library‘], function(cmp, lib) {
    return { init: ‘initialized:\ncomponent: ‘ + cmp.description +
        ‘\nand library: ‘ + lib.version};
});

require([‘framework‘], function(framework) {
    alert(framework.init);
});

define(‘library‘, [], function() {
    return { version: ‘0.0.1‘ };
});

define(‘component‘, [‘library‘], function(lib) {
    return { description: ‘uses library version: ‘ + lib.version };
});
Promise实现简易AMD加载器

原文地址    http://curiosity-driven.org/amd-loader-with-promises

Promise实现简易AMD加载器

上一篇:POJ 3984 迷宫问题


下一篇:安装CDH5时出错 5.68.168.192.in-addr.arpa domain name pointer bogon.