Last active
June 12, 2016 19:50
-
-
Save zachdunn/fd2d30e3b511b9a1ff2a90e02dc552a8 to your computer and use it in GitHub Desktop.
Promisify Papa Parse for Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
// Papa Parse: http://papaparse.com/ | |
// Allows Angular apps to neatly inject `Papa` in components. | |
angular.module('appName').constant('Papa', window.Papa); | |
}).call(this); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
function papaDecorator ($delegate, $injector, _) { | |
var $q, | |
loadDeps; | |
// We have to inject these during runtime to avoid circular dependencies | |
// from things like `moment` or `$translate` | |
loadDeps = function () { | |
if (!$q) { | |
$q = $injector.get('$q'); | |
} | |
}; | |
// Promisify Papa Parse | |
// Example: Papa.asyncParse(file).then().catch() | |
$delegate.Papa.asyncParse = function (file, options) { | |
var deferred, | |
promisifiedCallbacks; | |
loadDeps(); | |
deferred = $q.defer(); | |
promisifiedCallbacks = { | |
complete: function (response) { | |
deferred.resolve(response.data); | |
}, | |
error: deferred.reject | |
}; | |
Papa.parse(file, _.assign({}, options, promisifiedCallbacks)); | |
return deferred.promise; | |
}; | |
return $delegate; | |
} | |
angular.module('appName') | |
.config([ | |
'$provide', | |
function ($provide) { | |
$provide.decorator('$window', [ | |
'$delegate', | |
'$injector', | |
'_', | |
papaDecorator | |
]); | |
} | |
]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment