promised.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. define([], {
  2. load: function (name, req, load) {
  3. if (!/^require\$promised\$/.test(name)) {
  4. load.error(new Error("I can only promisize 'require', not '" + name.split('$')[0] + "'. Use 'promised!require' as module name."));
  5. return;
  6. }
  7. if (typeof Promise !== "function" || !Promise.prototype.then) {
  8. load.error(new Error("Promise not present or has not Promise API."));
  9. return;
  10. }
  11. var fn = function (deps, callback, errback) {
  12. if (typeof deps === "string") {
  13. return req.apply(this, arguments);
  14. }
  15. var promise = new Promise(function (resolve, reject) {
  16. req(deps, function () {
  17. resolve(Array.prototype.slice.call(arguments));
  18. }, reject);
  19. });
  20. if (callback) promise = promise.then(function (modules) {
  21. callback.apply(null, modules);
  22. });
  23. if (errback) promise = promise.then(null, errback);
  24. return promise;
  25. };
  26. Object.keys(req).forEach(function (k) {
  27. fn[k] = req[k];
  28. });
  29. load(fn);
  30. },
  31. normalize: function (name, normalize) {
  32. return normalize(name) + "$promised$" + Date.now().toString(36) + Math.random().toString(32).slice(1);
  33. }
  34. });