Promise实现简易AMD加载器

时间:2022-12-06 02:14:36

在最新的Chrome和FF中已经 实现了Promise。有了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);
});
}

使用方式如下

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 };
});

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