Skip to content

Instantly share code, notes, and snippets.

@killroy42
Created August 29, 2015 09:29
Show Gist options
  • Save killroy42/09a80ed4b51966b427e3 to your computer and use it in GitHub Desktop.
Save killroy42/09a80ed4b51966b427e3 to your computer and use it in GitHub Desktop.
Core Tools
function require(urls) {
if(!(urls instanceof Array)) urls = [urls];
return Promise.all(urls.map(function(url) {
return fetch(url)
.then(function (response) {
return response.text();
})
.then(function(scriptText) {
var _module = {exports: {}};
eval('(function (module, exports) { ' + scriptText + '\n//*/\n})(_module, _module.exports);\n//@ sourceURL=' + url);
return _module.exports;
});
}));
}
function imgToPromise(img) {
return new Promise(function(resolve, reject) {
if(img.complete) return resolve(img);
img.onload = function() {
resolve(img);
};
img.onerror = function() {
reject(new Error('Error loading image: '+img.src));
};
});
};
function promiseSer(tasks, f) {
return tasks.reduce(function(p, task, idx) {
return p.then(function() {
f(task, idx);
});
}, Promise.resolve());
}
function promisePar(tasks, f) {
return Promise.all(tasks.map(function(task, idx) {
return f(task, idx);
}));
}
<script src="http://rawgit.com/github/fetch/master/fetch.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment